【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" />
相关推荐
烟话62 天前
MVVM核心机制:属性通知与命令绑定解析
wpf
不知名君3 天前
WPF 的原生窗体标题栏主题自适应系统深浅主题
wpf
碎碎念的安静3 天前
WPF 与 Qt 进程间通信(IPC)
开发语言·qt·wpf
军训猫猫头4 天前
7.带输入参数的线程启动 C# + WPF 完整示例
开发语言·前端·c#·.net·wpf
周杰伦fans4 天前
WPF Prism 框架完全入门指南:从环境搭建到弹窗导航实战
wpf
雨浓YN4 天前
WPF MVVM 模式(无调库)项目创建笔记
笔记·wpf
周杰伦fans5 天前
.NET AOT技术深度解析:为什么WPF不支持而Avalonia/UWP支持?
.net·wpf
雨浓YN5 天前
WPF MVVM 模式(调Prism库)项目创建笔记 —— 包含C++/CLI OpenCV互操作
c++·笔记·wpf
七夜zippoe5 天前
DolphinDB数据模型:表、分区与分布式表
分布式·wpf·数据模型··dolphindb
一念春风6 天前
Qwen2.5 (AI模型 PC搭建)
人工智能·ai·c#·wpf·模型