26

In MVVM pattern, how to notify all properties of the view model has changed? I don' t want to call all notifypropertychanged event of all properties.

I have an entity class and in view model I wrote all of the public fields of the entity as public properties. I want to rebind new entity and just write a single line of code to notify that all properties has changed?

Thanks for your help.

mkus
  • 3,357
  • 6
  • 37
  • 45

2 Answers2

58

Just raise the PropertyChanged event with an empty string as the property name :

OnPropertyChanged(String.Empty);
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
  • 3
    Yes, firing the PropertyChanged event with null or an empty string does the trick. – Barracoder Aug 06 '10 at 14:47
  • Hi Thomas, is this applicable for Uwp solutions too? I see in some projects that this is not working well in Windows 8.1 or Universal Windows Platform Apps. Thank's for all! – soydachi Mar 27 '17 at 13:41
  • @dachibox, I've never used UWP, so I don't know... but I would expect it to work as well. – Thomas Levesque Mar 27 '17 at 14:31
  • I just post this question as an independent thread if anyone knows this issue I appreaciate it. http://stackoverflow.com/questions/43049019/notifying-all-properties-of-the-viewmodel-has-changed-with-null-or-string-empty – soydachi Mar 27 '17 at 14:41
  • "Note that in a UWP application, String.Empty must be used rather than null." – Hans GD Jul 20 '23 at 20:04
0

Ok what I understood from your question is this..

View <> ViewModel <> Entity (with a bunch of properties)

View is bound to ViewModel, which delegates to Entity. You now want to replace the backing entity and signal the view to refresh to update to the newer entity.

I'd suggest implementing an indexer in the ViewModel which takes in a string (the name of the backing property). The ViewModel can be used as a cache if required, delegating to the backing entity only on a miss.

When you replace the entity, the viewModel clears its cache and fires NotifyPropertyChanged (in the indexer set) with String.Empty or null. Which I learned today, indicates all properties have changed.

This way you don't create n delegating properties in the ViewModel. A google search result shows that it has been tried at least once with success.

Gishu
  • 134,492
  • 47
  • 225
  • 308