Click or drag to resize
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:

This topic contains the following sections:

Primitive Properties

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:

C#
public string ProviderHostName
{
    get { return this.providerHostName; }
    set { this.SetValue(ref this.providerHostName, value); }
}
Note 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:

C#
public string Title
{
    get
    {
        return "Lawo Glow Analyzer Proxy " +
            System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
    }
}
Composite Properties

The getter of a composite property returns a value, which cannot directly be shown on the GUI:

C#
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.

Collection Properties

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:

C#
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.