In wpf we often use following pattern for bindable properties:
private Foo _bar = new Foo();
public Foo Bar
{
get { return _bar; }
set
{
_bar = value;
OnPropertyChanged();
}
}
public void OnPropertyChanged([CallerMemberName] string property = "")
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
CallerMemberNameAttribute
does nice magic, generating for us "Bar"
parameter from setter name.
However, often there are properties without setter or dependent properties:
private Foo _bar;
public Foo Bar
{
get { return _bar; }
set
{
_bar = value;
OnPropertyChanged();
}
}
public bool IsBarNull
{
get { return _bar == null; }
}
In given example, when Bar
is changed then IsBarNull
needs event too. We can add OnPropertyChanged("IsBarNull");
into Bar
setters, but ... using string
for properties is:
- ugly;
- hard to refactor (VS's "Rename" will not rename property name in
string
); - can be a source of all kind of mistakes.
WPF exists for so long. Is there no magical solution yet (similar to CallerMemberNameAttribute
)?