Change Notification |
The View holds a copy of the data provided by the ViewModel, which is why the View needs to be notified when the data in the ViewModel changes. All XAML-based View objects automatically look for implementations of INotifyPropertyChanged and INotifyCollectionChanged and subscribe to the provided events as appropriate. ViewModel developers can reuse the following implementations:
NotifyPropertyChanged: ViewModel implementations as well as the types of composite properties usually derive from this base class.
Collection properties are usually of the type ObservableCollectionT or ReadOnlyObservableCollectionT.
This topic contains the following sections:
A primitive property provides data that can directly be shown in the View (e.g. string, double, int, etc.). A property where the value may change while it is being displayed in the View typically looks as follows:
public string ProviderHostName { get { return this.providerHostName; } set { this.SetValue(ref this.providerHostName, value); } }
Note |
---|
SetValue does its magic with the CallerMemberNameAttribute. SetValue should therefore only ever be called directly from a setter of a property. |
Of course, properties that never change their value do not need to concern themselves with change notification:
public string Title { get { return "Lawo Glow Analyzer Proxy " + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; } }
The getter of a composite property returns a value, which cannot directly be shown on the GUI:
public ConnectionViewModel ConsumerConnection => this.consumerConnection;
In this case the property value never changes. Of course, in general such properties can change their value too. Then, change notification needs to be implemented by calling SetValue in the property setter just like a primitive property setter does.
Since the View will bind to properties of the returned value, ConnectionViewModel must also implement INotifyPropertyChanged, here again by deriving from NotifyPropertyChanged.
Whenever a View needs to display multiple items in a list, the associated ViewModel typically offers the necessary data through a property getter that returns a collection implementing the INotifyCollectionChanged interface:
public ReadOnlyObservableCollection<Event> Events => this.readOnlyEvents;
The .NET framework implementations ObservableCollectionT and ReadOnlyObservableCollectionT are almost always sufficient. The former should only be used if the View itself can directly add and/or remove items. The latter is preferable when such operations are offered through ViewModel methods and of course also when the collection is immutable from the View.