nuclear sweet
nuclear sweet

Reputation: 1133

Execute method in viewmodel when property changed

I have some ViewModel with string property Name

My ViewModel inherit from ViewModelBase : INotifyPropertyChanged

...
    private string _name;
    public string Name
    {
        get { return _name; }
        set { SetField(ref _name, value, "Name"); }
    }

...

public class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }

    protected bool SetField<T>(ref T field, T value, string propertyName)
    {
        if (EqualityComparer<T>.Default.Equals(field, value)) return false;
        field = value;
        OnPropertyChanged(propertyName);
            return true;
    }
}

I want to execute some logic when my property Name change its value (on user input). My ViewModel will have alot of such properies and i will have alot of ViewModels with same property processing.

How should i run method that process chaneged propery in a right way? Should i subscribe on PropertyChanged event in my ViewModel, then use switch on string property name to detect actual changed property and then use it value? Or should i just run my method from setter?

Is there any patterns for such interactions?

Upvotes: 1

Views: 3864

Answers (1)

kkyr
kkyr

Reputation: 3845

Since your SetField method returns true if the property has changed, I would call my method in the setter if true is returned.

...
public string Name
{
    get { return _name; }
    set 
    { 
        if (SetField(ref _name, value, "Name"))
            MyMethod();
    }
}
...

Upvotes: 4

Related Questions