【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" />
相关推荐
松☆1 天前
终章:构建完整生态——Flutter + OpenHarmony 分布式应用开发全景指南(含性能调优与发布实践)
flutter·wpf
松☆1 天前
高阶实战:基于 Flutter 的 OpenHarmony 分布式软总线多设备协同应用开发
wpf
松☆1 天前
终极挑战:Flutter 应用在 OpenHarmony 上实现跨设备无缝流转(Continuation)与软总线协同
flutter·wpf
她说彩礼65万1 天前
WPF SynchronizationContext的使用
wpf
云雾J视界1 天前
分布式AI框架选型困局:SintolRTOS vs Ray vs Horovod,性能压测全解析
tensorflow·wpf·horovod·ray·分布式ai·sintolrtos
豫狮恒2 天前
OpenHarmony Flutter 分布式多模态交互:融合音视频、手势与环境感知的跨端体验革新
flutter·wpf·openharmony
豫狮恒2 天前
OpenHarmony Flutter 分布式数据共享实战:从基础存储到跨设备协同
flutter·wpf·openharmony
500842 天前
鸿蒙 Flutter 隐私合规:用户授权中心与数据审计日志
flutter·华为·开源·wpf·音视频
豫狮恒2 天前
OpenHarmony Flutter 分布式软总线实战:跨设备通信的核心技术与应用
flutter·wpf·harmonyos
Hello.Reader2 天前
Flink SQL 的 LIMIT 子句语义、坑点与实战技巧
sql·flink·wpf