MVVM: Trigger method on property changed with Fody.PropertyChanged

1k Views Asked by At

I'd like to run a method on property changed. I'd like my code to compile to something like this:

public string Property
    {
        get { return _property; }
        set
        {
            _property= value;
            IWantToCallFromHere(); // I want to inject this call
            NotifyPropertyChanged();
        }
    }
1

There are 1 best solutions below

0
On

This is described in the Wiki in the page named On_PropertyName_Changed.

Essentially you add a method with the naming convention private void OnYourPropertyNameChanged()

A complete example of what you would like to achieve is as follows:

public string Property
{
    get; set;
}

private void OnPropertyChanged()
{
    IWantToCallFromHere();
}

which gets translated into

private string _property;
public string Property
{
    get => _property; 
    set
    {
        if(_property != value)
        {
            _property = value;
            OnPropertyChanged();
            NotifyPropertyChanged();
        }
    }
}

private void OnPropertyChanged()
{
    IWantToCallFromHere();
}