【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" />
相关推荐
JosieBook6 小时前
【开源】一款开源、跨平台的.NET WPF 通用权限开发框架 (ABP) ,功能全面、界面美观
.net·wpf
你我约定有三6 小时前
分布式微服务--Nacos作为配置中心(二)
java·分布式·spring cloud·微服务·架构·wpf·负载均衡
界面开发小八哥9 小时前
界面组件DevExpress WPF中文教程:网格视图数据布局 - 数据单元格
.net·wpf·界面控件·devexpress·ui开发
三千道应用题19 小时前
WPF&C#超市管理系统(4)入库管理
c#·wpf
freesheep7201 天前
WPF使用PreviewTextInput事件限制用户输入
c#·wpf
c#上位机3 天前
wpf之ControlTemplate
wpf
kyranhan5 天前
WPF,窗口拖动事件与窗口内控件点击事件
wpf
孟婆来包棒棒糖~5 天前
SpringCloude快速入门
分布式·后端·spring cloud·微服务·wpf
Humbunklung5 天前
C# WPF 实现读取文件夹中的PDF并显示其页数
pdf·c#·wpf·npoi·gemini·itext
wangnaisheng5 天前
【WPF】NumericUpDown的用法
wpf