New C# 5.0 release introduced something to get rid of "magic strings" in INotifyPropertyChanged implementation like:
OnPropertyChanged("CustomerName");
Now it is possible to write just:
OnPropertyChanged();
It is possible due to CallerMemberName in method definition:
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{ ... }
It is much more refactoring friendly than "magic strings" way and faster than lambda expressions, but I wonder how can we call multiple times OnPropertyChanged from one set accessor. For example if we wanted something like this:
public int Width
{
get
{
return width;
}
set
{
width = value;
OnPropertyChanged("Width");
OnPropertyChanged("Height");
}
}
How can we do this with CallerMemberName way and avoid using "magic strings" and lambda expressions?
I also wonder how can we avoid using "magic strings" in IDataError info:
public string Error
{
get;
private set;
}
public string this[string columnName]
{
get
{
if (columnName == "Name")
{
if (String.IsNullOrWhiteSpace(Name))
Error = "Name cannot be null or empty.";
else
Error = null;
}
return Error;
}
}
I am new to MVVM so maybe I overlooked some clever way to deal with "magic strings", however I did some research and found nothing.
The simple answer is, that you can't do that. As the name CallerMemberName
indicates, it will contain the name of the caller.
For cases where you want to raise PropertyChanged
for another than the current one, you will have to use one of the "old" ways.
In IDataErrorInfo
you also have to use one of those ways, there is no alternative.