【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" />
相关推荐
芒鸽3 小时前
HarmonyOS 分布式开发实战:设备协同、数据共享与跨设备迁移
分布式·wpf·harmonyos
Volunteer Technology3 小时前
Flink状态管理与容错(二)
大数据·flink·wpf
happyprince1 天前
07_verl-Trainer模块详解
人工智能·架构·wpf·强化学习
bugcome_com1 天前
WPF + Prism 技术指南与实战项目(二、模板搭建)
wpf
小满Autumn1 天前
log4net 日志框架 — 从配置到实战速查手册
笔记·c#·.net·wpf·上位机·log4net
政沅同学2 天前
基于 C# WPF + HALCON 的工业视觉算法工具框架(开源)
开发语言·c#·wpf
happyprince2 天前
03_verl-设计理念与核心原理
wpf
happyprince2 天前
01_verl-项目概览与架构总览
架构·wpf
Chris _data2 天前
# WPF 学习记录( 第二天)
学习·wpf
myenjoy_13 天前
大规模采集架构——从单台网关到千点集群
架构·wpf