首页 > 解决方案 > MVVM 灯。当属性的值真正改变时执行方法的正确方法

问题描述

此代码允许在设置属性时执行该方法。它执行的次数与设置属性的次数一样多。我想知道只有在属性值真正改变时才执行该方法的变体。

public const string MyPropertyPropertyName = "MyProperty";

        private bool _myProperty = false;
      
        public bool MyProperty
        {
            get
            {
                return _myProperty;
            }
            set
            {
                Set(MyPropertyPropertyName, ref _myProperty, value);

                DoSomething();
            }
        }


        private void DoSomething()
        {

            // DO YOUR WORK

        }

标签: wpfpropertiesmvvm-light

解决方案


Set方法应返回一个bool值,该值指示该属性是否被实际设置:

set
{
    if (Set(MyPropertyPropertyName, ref _myProperty, value))
        DoSomething();
}

如果它没有返回值,您应该修改它或使用您自己的自定义Set方法:

protected bool Set<T>(string propertyName, ref T storage, T value)
{
    if (Equals(storage, value))
        return false;

    storage = value;
    OnPropertyChanged(propertyName);

    return true;
}

推荐阅读