自己实现一个WPF MVVM 模式 的属性绑定和命令绑定模型

191 阅读1分钟
    public abstract class MvvmNotifyPropertyChanged : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
 
        protected virtual void SetProperty<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
        {
            if (EqualityComparer<T>.Default.Equals(field, value)) return;
 
            field = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
 
        [NotifyPropertyChangedInvocator]
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public class MvvmCommand : ICommand
    {
        public Func<object, bool> CanExecuteCommand = null;
        public Action ExecuteCommand = null;
        public event EventHandler CanExecuteChanged;
 
        public MvvmCommand(Action executeCommand)
        {
            this.ExecuteCommand = executeCommand;
        }
 
        public MvvmCommand(Action executeCommand, Func<object, bool> canExecuteCommand)
        {
            this.ExecuteCommand = executeCommand;
            this.CanExecuteCommand = canExecuteCommand;
        }
 
        public bool CanExecute(object parameter)
        {
            if (CanExecuteCommand != null)
                return CanExecuteCommand(parameter);
            return true;
        }
 
        public void Execute(object parameter)
        {
            ExecuteCommand?.Invoke();
        }
 
        public void RaiseCanExecuteChanged()
        {
            if (CanExecuteChanged != null) CanExecuteChanged(this, EventArgs.Empty);
        }
    }
    public class MvvmCommand<T> : ICommand
    {
        public Func<T, bool> CanExecuteCommand = null;
        public Action<T> ExecuteCommand = null;
        public event EventHandler CanExecuteChanged;
 
        public MvvmCommand(Action<T> executeCommand)
        {
            this.ExecuteCommand = executeCommand;
        }
 
        public MvvmCommand(Action<T> executeCommand, Func<T, bool> canExecuteCommand)
        {
            this.ExecuteCommand = executeCommand;
            this.CanExecuteCommand = canExecuteCommand;
        }
 
        public bool CanExecute(object parameter)
        {
            if (CanExecuteCommand != null)
                return CanExecuteCommand((T)parameter);
            return true;
        }
 
        public void Execute(object parameter)
        {
            if (!CanExecute(parameter)) return;
            ExecuteCommand?.Invoke((T)parameter);
        }
 
        public void RaiseCanExecuteChanged()
        {
            CanExecuteChanged?.Invoke(this, EventArgs.Empty);
        }
    }

以上是命令绑定

使用效果如下:

可以在 xaml 里 引用当前的 viewmodel,方便页面属性引用和运行实例绑定生成。效果不错!