csharp 可绑定类减少mvvm中的样板代码(实现INotifyPropertyChanged)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 可绑定类减少mvvm中的样板代码(实现INotifyPropertyChanged)相关的知识,希望对你有一定的参考价值。

namespace Helpers
{
    ///<summary>
    ///     Reduce mvvm boilerplate
    ///
    ///     Usage:
    ///     public class MyViewModel : Bindable {
    ///          // Now this property supports INotifyPropertyChanged
    ///          public string MyProperty 
    ///          {
    ///               get { return Get<string>(); }
    ///               set { Set(value); }
    ///          }
    ///     }
    ///</summary>
    public class Bindable : INotifyPropertyChanged
    {
        private readonly Dictionary<string, object> _properties
            = new Dictionary<string, object>();

        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        ///     Gets the value of a property
        /// </summary>
        protected T Get<T>([CallerMemberName] string name = null)
        {
            object value;
            if (_properties.TryGetValue(name, out value))
                return value == null ? default(T) : (T) value;
            return default(T);
        }

        /// <summary>
        ///     Sets the value of a property
        /// </summary>
        protected void Set<T>(T value, [CallerMemberName] string name = null)
        {
            if (Equals(value, Get<T>(name)))
                return;
            _properties[name] = value;
            OnPropertyChanged(name);
        }

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

以上是关于csharp 可绑定类减少mvvm中的样板代码(实现INotifyPropertyChanged)的主要内容,如果未能解决你的问题,请参考以下文章

Android安卓进阶技巧之Kotlin结合Jetpack构建MVVM

csharp 单个文件中的C#MVVM公共类。用法示例:https://heiswayi.github.io/2016/mvvm-common-classes-in-single-file

当 MVVM 中的属性更改时通知可观察集合

wpf MVVM框架基础

WPF MVVM中的绑定复选框问题

mvvm