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

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

  • 相关阅读:
    Leetcode 532.数组中的K-diff数对
    Leetcode 529.扫雷游戏
    定增游戏(三)
    套利不归路(五)
    定增游戏(一)
    套利不归路(四)
    套利不归路(三)
    套利不归路(二)
    套利不归路(一)
    减持大逃亡(二)
  • 原文地址:https://www.cnblogs.com/catzhou/p/13720257.html
Copyright © 2020-2023  润新知