TheOne TheOne - 3 months ago 11
C# Question

How to subscribe to certain properties event

I have an object that has many properties. Each time a property changes an event is raised. For performance issue, I want in the view model to subscribe to certain properties event without changing the business object.

I know I can check for the property name in the event handler. But I don't want to go this route since it is a complicated business that have too many properties.

For more clarification, lets say I have the Car class with these properties.
I want to listen to the events of property A,D,G and I want to ignore the rest.

Thank you

class Car : INotifyPropertyChanged
{
public string A {get {...} set {...}}
public string B {get {...} set {...}}
public string C {get {...} set {...}}
public string D {get {...} set {...}}
public int E {get {...} set {...}}
public int F {get {...} set {...}}
public int G {get {...} set {...}}

...
}

Answer

If you want the event handler to only handle one property then only have it handle one property. You can subscribe to the property changed event multiple times

public class Example
{
    private readonly Car _car;
    public Example(Car car)
    {
        _car = car;
        _car.PropertyChanged += HandleA;
        _car.PropertyChanged += HandleD;
        _car.PropertyChanged += HandleG;
    }

    private void HandleA(object sender, PropertyChangedEventArgs args)
    {
        if(args.PropertyName == "A" || String.IsNullOrEmpty(args.PropertyName))
        {
            //Do logic for A
        }
    }

    private void HandleD(object sender, PropertyChangedEventArgs args)
    {
        if(args.PropertyName == "D" || String.IsNullOrEmpty(args.PropertyName))
        {
            //Do logic for D
        }
    }

    private void HandleG(object sender, PropertyChangedEventArgs args)
    {
        if(args.PropertyName == "G" || String.IsNullOrEmpty(args.PropertyName))
        {
            //Do logic for G
        }
    }
}

The IsNullOrEmpty checks are because a null or empty property name means all properties where updated.

Comments