【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" />
相关推荐
Aevget9 小时前
DevExpress WPF中文教程:Data Grid - 如何绑定到有限制的自定义服务(四)?
wpf·界面控件·devexpress·ui开发·.net 10
棉晗榜13 小时前
wpf DataGrid控制列是否显示,DataGrid列不会触发Visibility的转换器
wpf
超级种码14 小时前
Redis:Redis高可用——副本、哨兵和集群
数据库·redis·wpf
棉晗榜14 小时前
wpf给Border添加闪烁边框
wpf
Derrick_itRose14 小时前
DevExpress笔记WPF(2)Data Editors and Controls(基础编辑器)
笔记·编辑器·wpf
He BianGu14 小时前
【笔记】WPF的Binding中AsyncState的使用方式
笔记·wpf
曹天骄1 天前
Cloudflare KV 使用教程(基于 Wrangler 项目)
wpf
摘星编程1 天前
Flutter for OpenHarmony 实战:Dialog 对话框详解
flutter·wpf
ou.cs1 天前
WPF TreeView 自动展开所有节点:附加行为(Attached Behavior)保姆级实现教程
c#·.net·wpf
一念春风2 天前
可视化视频编辑(WPF C#)
开发语言·c#·wpf