zoukankan      html  css  js  c++  java
  • [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);
        }
    }
    

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

  • 相关阅读:
    hdu4059 The Boss on Mars
    cf475D CGCDSSQ
    HDU
    cf1447D Catching Cheaters
    cf1440 Greedy Shopping
    Treats for the Cows
    dp废物学会了记录路径
    D. Jzzhu and Cities
    cf1359D Yet Another Yet Another Task
    关于sg函数打表的理解
  • 原文地址:https://www.cnblogs.com/catzhou/p/13720257.html
Copyright © 2011-2022 走看看