Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

I know this question is about C# 5.0, but if people still have questions of thise nature please check out c# 6.0. C# 6.0 Has a great way to solve this problem. Check out the nameof keyword. I wrote a little post about it if anyone is interested: c# 6.0 solves magic strings problem

This will help: "Kind Of Magic" Effortless INotifyPropertyChanged

http://visualstudiogallery.msdn.microsoft.com/d5cd6aa1-57a5-4aaa-a2be-969c6db7f88a

as an example for adding it to one property:

[Magic] 
public string Name { get { return _name; } set { _name = value; } } 
string _name;

Another example for adding it to all the class properties:

[Magic] 
public class MyViewModel: INotifyPropertyChanged 
{ 
  public string Name { get; set; } 
  public string LastName { get; set; } 
  ..... 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top