【WPF】MVVM模式实现数据绑定以及Command事件绑定

发布于:2025-03-26 ⋅ 阅读:(34) ⋅ 点赞:(0)

1.引用类

using System.ComponentModel

2.创建Command自定义类

 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事件点击

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.界面按钮绑定事件

<Button
   Margin="0,0,5,0"
    Command="{Binding DoubleClickNotifyCommand }"
    Content="{DynamicResource Setting_File}"
    FontSize="20"
    Foreground="White" />

网站公告

今日签到

点亮在社区的每一天
去签到