1

With WPF and MVVM, properties of the ViewModel are bound to UI elements. When a property changes, its set accessor calls OnPropertyChanged which in turn raises the PropertyChanged event of the INotifyPropertyChanged interface.

But it is possible to call OnPropertyChanged (with the property name as argument) from anywhere in the ViewModel (and then you can't use the CallerMemberName attribute).

Now I'd like to ask you: how do you handle such cases? Do you call OnPropertyChanged from other places than property_set? Or do you change your code such that you call property_set? Or other ideas?

  • FWIW I've struggled with this myself. I inevitably need to tell the framework that some VM property changed, even though it didn't, in order to get an ICommand's CanExecute method to trigger when something in my business model changed. – RubberDuck Jul 26 '16 at 11:34
  • @RubberDuck You can force ICommand CanExecutes to be re-evaluated by calling CommandManager.InvalidateRequerySuggested() – 17 of 26 Jul 26 '16 at 13:41
  • @17of26 that class doesn't exist in UWP. – RubberDuck Jul 26 '16 at 13:42
2

Like everything else, it depends on the individual case. Typically, your simple properties have a get and a set. You call the set and it, in turn, raises the property change notification.

One common case where you need to manually raise property change notifications is with derived properties. These don't usually have a set and can change based on modifications to other properties.

A contrived example:

public int ASquared => _a * _a;

public int A 
{
    get { return _a; }
    set 
    {
        if (_a == value)
            return;

        _a = value;
        RaisePropertyChanged();
        RaisePropertyChanged(nameof(ASquared));
    }
}
private int _a;
  • This would be a better answer if it showed an example of the get only derived properties you mentioned. – RubberDuck Jul 26 '16 at 13:43
  • 1
    That's what ASquared is, although I botched the syntax. Fixed now. – 17 of 26 Jul 26 '16 at 13:50
  • 1
    With the C#6 features (nameof), renaming of a property doesn't cause so many problems as before... – Bernhard Hiller Jul 28 '16 at 14:03
0

I never call PropertyChanged directly, I use this very simple but extremely useful library:

https://github.com/StephenCleary/CalculatedProperties/blob/master/README.md

It is really a "formula engine" for MVVM that raises notifications from setters and for affected calculated readonly properties too (just like formulas in spreadsheets formulas react to change of source values)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.