【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" />
相关推荐
Aevget2 小时前
界面控件DevExpress WPF v25.1新版亮点:PDF Viewer功能全新升级
pdf·wpf·界面控件·devexpress·ui开发
5***a9752 天前
后端配置中心选型,Nacos与Apollo
wpf
·心猿意码·2 天前
WPF转换器机制
wpf
她说彩礼65万2 天前
WPF命令
wpf
玖笙&2 天前
✨WPF编程进阶【7.3】集成动画(附源码)
c++·c#·wpf·visual studio
ifeng09182 天前
鸿蒙分布式调试挑战:跨设备数据流转与连接稳定性
分布式·wpf·harmonyos
Macbethad2 天前
如何使用WPF做工控主页
wpf
Aevget3 天前
DevExpress WPF中文教程:Data Grid - Service(服务)示例
wpf·界面控件·devexpress·ui开发
Macbethad3 天前
WPF工控软件的设计方案
wpf
Macbethad5 天前
使用WPF编写一个读取串口的程序
wpf