【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" />
相关推荐
TA远方3 小时前
【C#】一个简单的http服务器项目开发过程详解
服务器·http·c#·wpf·web·winform·console
陈奕昆10 小时前
2.1HarmonyOS NEXT开发工具链进阶:DevEco Studio深度实践
华为·wpf·harmonyos
Dr.多喝热水12 小时前
WPF prism
windows·wpf
Hare_bai1 天前
WPF响应式UI的基础:INotifyPropertyChanged
ui·c#·wpf·xaml
上元星如雨1 天前
WPF 全局加载界面、多界面实现渐变过渡效果
wpf
Hare_bai1 天前
WPF的布局核心:网格布局(Grid)
ui·c#·wpf·交互·xaml
Hare_bai1 天前
WPF的基础控件:布局控件(StackPanel & DockPanel)
ui·c#·wpf·交互·xaml·visual studio
上元星如雨1 天前
WPF 按钮悬停动画效果实现
wpf
菜长江1 天前
WPF-Prism学习笔记之 “导航功能和依赖注入“
笔记·wpf
keke101 天前
WPF【09】WPF基础入门 (三层架构与MVC架构)
wpf