天天看點

自己實作一個WPF MVVM 模式 的屬性綁定和指令綁定模型

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));
        }
    }
           

以上是MVVM屬性綁定

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);
        }
    }
           

以上是指令綁定

使用效果如下:

自己實作一個WPF MVVM 模式 的屬性綁定和指令綁定模型
自己實作一個WPF MVVM 模式 的屬性綁定和指令綁定模型

可以在 xaml 裡  引用目前的 viewmodel,友善頁面屬性引用和運作執行個體綁定生成。效果不錯!

繼續閱讀