【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" />
相关推荐
源之缘-专注WPF开发5 小时前
全栈开发实战:WPF+FFmpeg+GIS,打造工业级雷达探测终端
ffmpeg·wpf·gis
张人玉9 小时前
C# WPF 折线图制作(可以连接数据库)
数据库·c#·wpf·sugar
闲人编程11 小时前
OpenTelemetry分布式追踪
分布式·wpf·trace·追踪·open telemetry·codecapsule
张人玉13 小时前
C# WPF 折线图制作笔记(LiveCharts 库)
笔记·c#·wpf·折线图·linechart
FuckPatience1 天前
WPF Matrix结构体方法ScaleAt的坐标系
wpf
我是小妖怪,潇洒又自在1 天前
springcloud alibaba(十)分布式事务
分布式·spring cloud·wpf
Poetinthedusk2 天前
设计模式-命令模式
windows·设计模式·c#·wpf·命令模式
棉晗榜2 天前
WPF印章水印, Border怎么悬浮在其他控件上面,类似盖章一样
wpf
张人玉2 天前
LiveCharts WPF MVVM 图表开发笔记
大数据·分布式·wpf·livecharts
武藤一雄2 天前
一款基于WPF开发的BEJSON转换工具
windows·c#·json·wpf