1. 程式人生 > 實用技巧 >WPF MVVM模式開發實現簡明教程 4 ViewModelBase

WPF MVVM模式開發實現簡明教程 4 ViewModelBase

如果多個ViewModel,則每個都要繼承INotifyPropertyChanged,並且有如下相同的方法

public event PropertyChangedEventHandler PropertyChanged;
 
        public void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

  

ViewModelBase 就是為了簡化以上程式碼而出現的

版本1

直接把之前的程式碼放到一個類裡,

呼叫時

publicclassButtonViewModel:ViewModelBase

ViewModelBase程式碼
using System.ComponentModel;
    using System.Runtime.CompilerServices;

    public abstract class ViewModelBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
 
        public void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

屬性

private string buttonContent;
 
public string ButtonContent
{
    get { return buttonContent; }
    set
    {
        buttonContent = value;
        OnPropertyChanged("ButtonContent");
    }
}

版本2

優化,不用傳propertyName 了

using System.ComponentModel;
    using System.Runtime.CompilerServices;

    public abstract class ViewModelBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

  屬性

private string buttonContent;
 
public string ButtonContent
{
    get { return buttonContent; }
    set
    {
        buttonContent = value;
        OnPropertyChanged();
    }
}

  

版本3

增加

protected virtual bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = "")
{
    if (EqualityComparer<T>.Default.Equals(storage, value))
        return false;
    storage = value;
    this.OnPropertyChanged(propertyName);
    return true;
}

  

屬性

private string buttonContent;
 
public string ButtonContent
{
    get { return buttonContent; }
    set { SetProperty(ref buttonContent, value); }
}

  進一步簡化程式碼

還有更簡化的,可以參考後面的DevExpress版本的,當然也可以自己實現