Best way to notify property change when field is depending on another

后端 未结 3 1365
粉色の甜心
粉色の甜心 2021-01-31 06:16

What is the best way in c# to notify property changed on an item\'s field without set but get depends on other fields ?

For example :



        
3条回答
  •  有刺的猬
    2021-01-31 07:09

    As far as I know, there is not built in method for that. I usually do like this:

    public class Foo : INotifyPropertyChanged
    {
        private Bar _bar1;
    
        public Bar Item
        {
            get { return _bar1; }
            set 
            { 
                 SetField(ref _bar1, value); 
                 ItemChanged();
            }
        }
    
        public string MyString
        {
            get { return _bar1.Item; }
        }
    
        private void ItemChanged()
        {
            OnPropertyChanged("MyString");
        }
    }
    
    public class Bar
    {
        public string Item { get; set; }
    }
    

    You don't have the notifying logic inside of the property this way. It is more maintainable in my opinion this way and it is clear what the method does.

    Also, I prefer to use this method I found somewhere on SO instead of the hardcoded name in the class (if the name of the property changes, it breaks).

    OnPropertyChanged("MyString"); becomes OnPropertyChanged(GetPropertyName(() => MyString));

    where GetPropertyName is:

    public static string GetPropertyName(Expression> propertyLambda)
    {
        if (propertyLambda == null) throw new ArgumentNullException("propertyLambda");
    
        var me = propertyLambda.Body as MemberExpression;
    
        if (me == null)
        {
            throw new ArgumentException("You must pass a lambda of the form: '() => Class.Property' or '() => object.Property'");
        }
    
        return me.Member.Name;
    }
    

    After this, every time I change the property as the name, I will have to rename the property everywhere I have GetPropertyName instead of searching for the hardcoded string values.

    I'm also curious about a built-in way to do the dependency, so I'm putting a favorite in there :)

提交回复
热议问题