【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" />
相关推荐
qq_340474024 小时前
5.02 WPF的 Combox、ListBox,slider、ProgressBar使用
wpf
fkdw5 小时前
.net farmework 4.8 类库中添加 wpf 窗体
.net·wpf
八股文领域大手子6 小时前
Spring多数据源环境下的事务与数据源切换
java·数据库·后端·mysql·spring·wpf
勘察加熊人7 小时前
c#使用wpf实现helloworld和login登录
开发语言·c#·wpf
她说彩礼65万7 小时前
WPF 自定义路由事件
wpf
qq_340474028 小时前
5.2.1 WPF 通过ItemControl自己做柱状图
java·开发语言·wpf
蓝点lilac9 小时前
C# 窗口过程消息处理 WndProc
wpf·winform·winapi
她说彩礼65万1 天前
WPF 依赖项属性
wpf
观无1 天前
WPF的MVVM的基础知识
wpf
她说彩礼65万2 天前
WPF 自定义行为AssociatedObject详解
wpf