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 :
public class Example : INotifyPropertyChanged
{
private MyClass _item;
public event PropertyChangedEventHandler PropertyChanged;
public MyClass Item
{
get
{
return _item;
}
protected set
{
_item = value;
OnPropertyChanged("Item");
}
}
public object Field
{
get
{
return _item.Field;
}
}
#if !C#6
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
#else
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
// => can be called in a set like this:
// public MyClass Item { set { _item = value; OnPropertyChanged();} }
// OnPropertyChanged will be raised for "Item"
}
#endif
}
What the best way to rise a PropertyChanged for "Field"
when setting Item
? I wanted to callOnPropertyChanged("Field");
when setting Item
but if I had many fields the code will quickly be ugly and unmaintainable.
Edit:
I wonder if there is a function/method/attribute working like this :
[DependOn(Item)]
public object Field
{
get
{
return _item.Field;
}
}
=> When Item
changes, all the depending fields will notify the property changed.
Does it exist ?
MyClass
– HydropicField
inMyClass
doesn't change, that the instance _item who is replaced by another. In my case,MyClass
contains a xml text. I do a webRequest obtain a new instance ofMyClass
and I save it on_item
._item.Field
can't notify property changed, becauseField
is only a get who parse the xml file. – Goofy