【WPF】MVVM模式实现数据绑定以及Command事件绑定

1.引用类

csharp 复制代码
using System.ComponentModel

2.创建Command自定义类

csharp 复制代码
 public class DelegateCommand : ICommand
    {
        public bool CanExecute(object parameter)
        {
            if (CanExecuteFunc == null)
                return true;
            return this.CanExecuteFunc(parameter);
        }

        public event EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
            if (ExecuteAction == null)
            {
                return;
            }
            this.ExecuteAction(parameter);
        }

        public Action<object> ExecuteAction { get; set; }
        public Func<object, bool> CanExecuteFunc { get; set; }

    }

3.ViewModel层实现数据绑定、Command事件点击

csharp 复制代码
public class MainViewModel : INotifyPropertyChanged
{
        public event PropertyChangedEventHandler PropertyChanged;
         public MainViewModel()
        {
          #必需初始化时就加载才生效
            this.SelectFileNameCommand = new DelegateCommand();
            this.SelectFileNameCommand.ExecuteAction = new Action<object>(this.SelectFileName);
        }
        
        /// <summary>
        /// 当前时间
        /// </summary>
        private string currentTimer;
        public string CurrentTimer
        {
            get
            {
                return currentTimer;
            }
            set
            {
                currentTimer = value;
                if (this.PropertyChanged != null)
                {
                    this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("CurrentTimer"));
                }
            }
        }

        public DelegateCommand DoubleClickNotifyCommand { get; set; }
        private void DoubleClickNotify(object parameter)
        {
            
        }

}

4.界面按钮绑定事件

csharp 复制代码
<Button
   Margin="0,0,5,0"
    Command="{Binding DoubleClickNotifyCommand }"
    Content="{DynamicResource Setting_File}"
    FontSize="20"
    Foreground="White" />
相关推荐
YrqnxehxDo12 小时前
相场模拟——合金,金属凝固模型,各向异性枝晶生长karma 合金凝固模型,选区激光熔融,激光增...
wpf
竟未曾年少轻狂1 天前
Spring Boot 项目集成 Redis
java·spring boot·redis·缓存·消息队列·wpf·redis集群
清风~徐~来2 天前
【视频点播系统】Redis-SDK 介绍及使用
数据库·redis·wpf
棉晗榜2 天前
WPF DataGrid鼠标滚不动,划不动解决
wpf
baivfhpwxf20232 天前
wpf自适应布局
wpf
艺杯羹2 天前
Git版本控制深度复盘:从入门到精通的完整指南
git·wpf·版本控制·git学习·git复盘
玄〤3 天前
RabbitMQ 入门篇总结(黑马微服务课day10)(包含黑马商城业务改造)
java·笔记·分布式·spring cloud·微服务·rabbitmq·wpf
向哆哆3 天前
CANN HCCL集合通信库在分布式训练中的高性能通信方案
分布式·wpf·cann
周杰伦fans4 天前
ai-skill开发WPF踩坑
wpf