Note: This posting is part of a series. See MVVM-Library for other parts and download.
As a ViewModel is – I already said before – databound to the UI it inherits NotifyKnownPropertyChanged to provide base support for Data Binding.
Data Binding to a WPF UI brings up another problem: The PropertyChanged event may only be raised in the UI thread.
In order to handle forbidden accesses from other threads and to make “Invoke”-scenarios possible, ViewModelBase remembers the dispatcher of the thread which created it. The methods for this purpose should be self-explanatory.
Note: ViewModel hides NotifyKnownPropertyChanged.OnPropertyChanged in order to perform a (debug-only) check ensuring it was called from the right thread. I thought a while if it would be better to make NotifyKnownPropertyChanged.OnPropertyChanged virtual and implement an auto-invoke solution. As ViewModel classes are not thread safe (in general), however, but may be able to deal with callbacks (etc.) executing in other threads, this approach is ok in my opinion. Derived classes must not call OnPropertyChanged from another thread – if they do though there will only be an error when using the debug build.
Today, I won’t post an sample project because ViewModelBase makes only sense if it is inherited. You can download the updated ViewModel project (without the sample for the last part) here: MVVM-Library.