【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" />
相关推荐
code bean5 小时前
【wpf】 WPF中实现动态加载图片浏览器(边滚动边加载)
wpf
baivfhpwxf20235 小时前
WPF 颜色间的转换 Color,Brush
wpf
Java Fans1 天前
WPF使用SQLite与JSON文本文件结合存储体侧平衡数据的设计与实现
sqlite·json·wpf
code_shenbing1 天前
WPF高级用法示例
c#·wpf·wpf高级
冰茶_1 天前
WPF之XAML基础
microsoft·微软·c#·.net·wpf·xaml·xamarin
呼Lu噜1 天前
WPF-遵循MVVM框架创建图表的显示【保姆级】
前端·后端·wpf
Zhen (Evan) Wang2 天前
.NET 6 + Dapper + User-Defined Table Type
sqlserver·c#·.net·wpf
界面开发小八哥3 天前
界面控件DevExpress WPF v25.1预览 - 支持Windows 11系统强调色
windows·wpf·界面控件·devexpress·ui开发·.net 9
军训猫猫头3 天前
89.WPF 中实现便捷的数字输入框:DecimalUpDown 控件的使用 WPF例子 C#例子.
开发语言·c#·wpf
Pasregret3 天前
缓存与数据库一致性深度解析与解决方案
数据库·缓存·wpf