[WPF 學習] 15.WPF MVVM之INotifyPropertyChanged接口的極簡實現

原來我寫了個基類this

public class VMBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public void RaisePropertyChanged([CallerMemberName] string propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

而後具體實現通常是這樣子的code

public class VMTest:VMBase
{
    private string _Test;
    public string Test
    {
        get => _Test;
        set
        {
            _Test = value;
            RaisePropertyChanged();
        }
    }
}

每次寫起來特別不爽,今天折騰了個新的基類,稍許簡單點get

public class VMBase : INotifyPropertyChanged
{
    private readonly Dictionary<string, object> CDField = new Dictionary<string, object>();

    public event PropertyChangedEventHandler PropertyChanged;

    public T G<T>([CallerMemberName] string propertyName = "")
    {
        object _propertyValue;
        if (!CDField.TryGetValue(propertyName, out _propertyValue))
        {
            _propertyValue = default(T);
            CDField.Add(propertyName, _propertyValue);
        }
        return (T)_propertyValue;
    }
    public void V(object value, [CallerMemberName] string propertyName = "")
    {
        if (!CDField.ContainsKey(propertyName) || CDField[propertyName] != (object)value)
        {
            CDField[propertyName] = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

具體實現就變成這個樣子了string

public class VMTest:VMBase
{
    public string Test
    {
        get => G<string>();
        set => V(value);
    }
}

只能說稍許簡單點,不知道還有沒有更方便的寫法。io