The model is the first "M" in MVVM. The model is usually a class containing the data that you want to expose via some kind of user interface.
Here is a very simple model class exposing a couple of properties:-
public class Customer : INotifyPropertyChanged
{
private string _forename;
private string _surname;
private bool _isValid;
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Customer forename.
/// </summary>
public string Forename
{
get
{
return _forename;
}
set
{
if (_forename != value)
{
_forename = value;
OnPropertyChanged();
SetIsValid();
}
}
}
/// <summary>
/// Customer surname.
/// </summary>
public string Surname
{
get
{
return _surname;
}
set
{
if (_surname != value)
{
_surname = value;
OnPropertyChanged();
SetIsValid();
}
}
}
/// <summary>
/// Indicates whether the model is in a valid state or not.
/// </summary>
public bool IsValid
{
get
{
return _isValid;
}
set
{
if (_isValid != value)
{
_isValid = value;
OnPropertyChanged();
}
}
}
/// <summary>
/// Sets the value of the IsValid property.
/// </summary>
private void SetIsValid()
{
IsValid = !string.IsNullOrEmpty(Forename) && !string.IsNullOrEmpty(Surname);
}
/// <summary>
/// Raises the PropertyChanged event.
/// </summary>
/// <param name="propertyName">Name of the property.</param>
private void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
This class implements the INotifyPropertyChanged
interface which exposes a PropertyChanged
event. This event should be raised whenever one of the property values changes - you can see this in action in the above code. The PropertyChanged
event is a key piece in the WPF data-binding mechanisms, as without it, the user interface would not be able to reflect the changes made to a property's value.
The model also contains a very simple validation routine that gets called from the property setters. It sets a public property indicating whether or not the model is in a valid state. I've included this functionality to demonstrate a "special" feature of WPF commands, which you'll see shortly. The WPF framework provides a number of more sophisticated approaches to validation, but these are outside the scope of this article.