[WPF 学习] 15.WPF MVVM之INotifyPropertyChanged接口的极简实现

原来我写了个基类

public class VMBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

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

然后具体实现一般是这样子的

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

每次写起来特别不爽,今天折腾了个新的基类,稍许简单点

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

具体实现就变成这个样子了

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

只能说稍许简单点,不知道还有没有更方便的写法。

[WPF 学习] 15.WPF MVVM之INotifyPropertyChanged接口的极简实现

上一篇:c#设计模式(4)——抽象工厂模式


下一篇:Windows Server 2016软路由配置