Question

There's plenty of code and example floating around on how you could use lambda expressions to raise INotifyPropertyChanged events for refactoring freiendly code. This is then typically used as:

NotifyOfPropertyChanged(() => PropertyName);

My question is, how would you achieve something similar on the receiving end of things, where you'd typcially have a switch statement of some sorts:

private void SomeObject_PropertyChanged(object sender, PropertyChangedEventArgs args)
{
    switch (args.PropertyName)
    {
        case "XYZ":
            break;
        //...
    }
}

Now it would be nice to somehow avoid using strings here as well so that things do not break when changing the property name...

As a half-way solution currently I just use an embedded class with public constants such as:

public class MyClass
{
    public static class Notifications
    {
        public const string Property1 = "Property1"
        //...
    }
    //...
}

And then on the receiving end:

private void SomeObject_PropertyChanged(object sender, PropertyChangedEventArgs args)
{
    switch (args.PropertyName)
    {
        case MyClass.Notifictions.Property1:
            break;
        //...
    }
}

This is somewhat better then pure strings as they only have to be maintained in one place and that is in the same class where you would make any changes to the property names as well but is still not a very satisfying solution...

Does someone know a better way?

Was it helpful?

Solution

It depends on what you actually want from the property. Assuming you want the value of the changed property, you can use reflection to get it:

private void SomeObject_PropertyChanged(object sender, PropertyChangedEventArgs args)
{
    object value = 
        sender.GetType().GetProperty(args.PropertyName).GetValue(sender, null);
}

If your needs are not fulfilled by reflection you can still use string comparison and not worry about the property name changing by using the same mechanism you're using in the NotifyPropertyChanged method. If you don't use one, you can use mine (code here):

private void SomeObject_PropertyChanged(object sender, PropertyChangedEventArgs args)
{
    if (args.PropertyName == ExtendedObject.GetPropertyName(_ => _.Property1)
    {
        // ...
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top