【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" />
相关推荐
李高钢5 小时前
开源控件库 HandyControl 介绍与简单实践:让 WPF 界面告别“上个世纪“
开源·wpf
旋生万物19 小时前
【终极实战】用Python从零“生成“一个宇宙:螺旋干涉模型的代码实现
开发语言·前端·人工智能·react.js·php·wpf
Now喔1 天前
WPF画刷介绍
wpf
李高钢1 天前
WPF/WinForms 客户端通过 gRPC 与后端通信:从 Proto 契约到流式调用的完整指南
wpf·grpc·winforms
一见已难忘2 天前
基于 Harmony 6.0 应用的宠物寄养预约系统实现
wpf·宠物
fl1768312 天前
基于C#WPF实现的内存加速球清理类似360加速球内存清理
开发语言·c#·wpf
李高钢2 天前
【WPF】高级 UI 与性能优化实战:从卡顿到丝滑
ui·性能优化·wpf
Chris _data3 天前
WPF 上位机开发学习笔记 - 第四天
笔记·学习·wpf
李高钢3 天前
除了 IDE,C#/WPF 开发者每天离不开的 10 个工具
ide·c#·wpf
李高钢3 天前
用 JetBrains Rider 写 WPF 的 15 个高效技巧:从 VS 转过来也值得看
wpf