【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" />
相关推荐
心平气和量大福大4 小时前
C#-WPF-控件-LiveChart图表-线性2(LineSeries)-数据绑定
开发语言·c#·wpf
whn19771 天前
oracle的节点2无法启动asm实例 提示PMON terminating the instance due to error 481
数据库·oracle·wpf
完美火龙篇 四月的友1 天前
WPF 笔迹延迟优化从硬件到软件的全链路分析
wpf
dalong101 天前
WPF:3D立方体
3d·wpf
Xin_ye100863 天前
第三章:内存泄漏的常见“案发现场”
c#·wpf
心平气和量大福大3 天前
C#-WPF-UserControl-生命周期(加载 退出)
开发语言·c#·wpf
czhc11400756633 天前
7.23:Claude code:注册->封表
wpf
心平气和量大福大4 天前
C#-WPF-控件-TextBox 数据绑定
开发语言·c#·wpf
listening7774 天前
HarmonyOS 6.1 全场景协同实战:从“单机”到“超级终端”的分布式重构
wpf
心平气和量大福大5 天前
C#-WPF-布局-Grid
c#·wpf·visual studio