Implementing INotifyPropertyChanged - does a better way exist?

前端 未结 30 2631
感情败类
感情败类 2020-11-21 05:23

Microsoft should have implemented something snappy for INotifyPropertyChanged, like in the automatic properties, just specify {get; set; notify;} I

30条回答
  •  -上瘾入骨i
    2020-11-21 05:30

    Whilst there are obviously lots of ways to do this, with the exception of the AOP magic answers, none of the answers seem to look at setting a Model's property directly from the view model without having a local field to reference.

    The issue is you can't reference a property. However, you can use an Action to set that property.

    protected bool TrySetProperty(Action property, T newValue, T oldValue, [CallerMemberName] string propertyName = null)
    {
        if (EqualityComparer.Default.Equals(oldValue, newValue))
        {
            return false;
        }
    
        property(newValue);
        RaisePropertyChanged(propertyName);
        return true;
    }
    

    This can be used like the following code extract.

    public int Prop {
        get => model.Prop;
        set => TrySetProperty(x => model.Prop = x, value, model.Prop);
    }
    

    Check out this BitBucket repo for a full implementation of the method and a few different ways of achieving the same result, including a method that uses LINQ and a method that uses reflection. Do note that these methods are slower performance wise.

提交回复
热议问题