I'm pretty new in WPF programming environment. I'm trying to write a program out using MVVM design pattern.
I've did some studies and read up some articles related to it and many of a time I came across this thing called
ViewModelBase
I know what it is.. But may I know specifically where should I begin with to be able to write out my own ViewModelBase? Like... Really understanding what's happening without getting too complicated. Thank you :)
The ViewModelBase abstract class is designed to serve as a base class for all ViewModel classes. It provides support for property change notifications. Instead of implementing the INotifyPropertyChanged interface in each individual ViewModel of your application, you can directly inherit the ViewModelBase class.
Google's interpretation of mvvm framework as can be seen on their android portal clearly says that it should be in the view model layer.
It's worth nothing to use MVVM frameworks if you don't know what's going on inside.
So let's go step by step and build your own ViewModelBase class.
ViewModelBase is class common for all your viewmodels. Let's move all common logic to this class.
Your ViewModels should implement INotifyPropertyChanged
(do you understand why?)
public abstract class ViewModelBase : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }
the [CallerMemberName]
attribute is not required, but it will allow you to write: OnPropertyChanged();
instead of OnPropertyChanged("SomeProperty");
, so you will avoid string constant in your code. Example:
public string FirstName { set { _firtName = value; OnPropertyChanged(); //instead of OnPropertyChanged("FirstName") or OnPropertyChanged(nameof(FirstName)) } get{ return _firstName;} }
Please note, that OnPropertyChanged(() => SomeProperty)
is no more recommended, since we have nameof
operator in C# 6.
It's common practice to implement properties that calls PropertyChanged like this:
public string FirstName { get { return _firstName; } set { SetProperty(ref _firstName, value); } }
Let's define SetProperty in your viewmodelbase:
protected virtual bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = "") { if (EqualityComparer<T>.Default.Equals(storage, value)) return false; storage = value; this.OnPropertyChanged(propertyName); return true; }
It simply fires PropertyChanged
event when value of the property changes and returns true. It does not fire the event when the value has not changed and returns false. The basic idea is, that SetProperty
method is virtual and you can extend it in more concrete class, e.g to trigger validation, or by calling PropertyChanging
event.
This is pretty it. This is all your ViewModelBase should contain at this stage. The rest depends on your project. For example your app uses page base navigation and you have written your own NavigationService for handling navigation from ViewModel. So you can add NavigationService property to your ViewModelBase class, so you will have access to it from all your viewmodels, if you want.
In order to gain more reusability and keep SRP, I have class called BindableBase which is pretty much the implementation of INotifyPropertyChanged as we have done here. I reuse this class in every WPF/UWP/Silverligt/WindowsPhone solution because it's universal.
Then in each project I create custom ViewModelBase class derived from BindableBase:
public abstract ViewModelBase : BindableBase { //project specific logic for all viewmodels. //E.g in this project I want to use EventAggregator heavily: public virtual IEventAggregator () => ServiceLocator.GetInstance<IEventAggregator>() }
if I have app, that uses page based navigation I also specify base class for page viewmodels.
public abstract PageViewModelBase : ViewModelBase { //for example all my pages has title: public string Title {get; private set;} }
I could have another class for dialogs:
public abstract DialogViewModelBase : ViewModelBase { private bool? _dialogResult; public event EventHandler Closing; public string Title {get; private set;} public ObservableCollection<DialogButton> DialogButtons { get; } public bool? DialogResult { get { return _dialogResult; } set { SetProperty(ref _dialogResult, value); } } public void Close() { Closing?.Invoke(this, EventArgs.Empty); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With