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

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

  • 相关阅读:
    get通配符
    常用正则表达式(合)
    2.A star
    1.序
    机器人运动规划04《规划算法》
    机器人运动规划03什么是运动规划
    6.2 性能优化
    6.1 内存机制及使用优化
    5.9 热修复技术
    5.8 反射机制
  • 原文地址:https://www.cnblogs.com/catzhou/p/13720257.html
Copyright © 2011-2022 走看看