Validation in MVVM - Silverlight part I
Purpose:
Values a user may enter in this form can be restricted by
the system (Silverlight application) and have to fit exactly to a list of
requirements or you just want to prevent problems when saving the data to the
database. Showing a message to the user when a value is entered is pretty
straight forward as I'll show you in the following example.
Using Validation Exception:
Validation exception occurs if an input value does not
match the expected data type, range or pattern of the data field. Values a user may enter in this form can be
restricted by the customer and have to fit exactly to a list of requirements or
you just want to prevent problems when saving the data to the database. For example, if a user enters an integer value
in a data field that expects a DateTime value, a validation exception occurs.
Validation in MVVM:
Step 1:
To implement MVVM
pattern create ViewModelBase, which implement INotifyPropertyChanged, to notify any change in view
model to XAML.
Example:
public abstract class ViewModelBase:INotifyPropertyChanged
{
#region
INotifyPropertyChangeImplemetation
public event PropertyChangedEventHandler PropertyChanged;
#endregion
INotifyPropertyChangeImplemetation
protected void
NotifyPropertyChange(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Step 2:
Create Silverlight application and a class for
ViewModel (class should implement ViewModelBase)
Example:
public class MainPageViewModel : ViewModelBase
Step 3:
Create required XAML as mentioned below, in XAML two
properties should be set to TRUE to notify any validation errors
ValidatesOnExceptions= True, it will throw
error if validation fails.
NotifyOnValidationError=True, it highlight the
control which contain error.
Mode=TwoWay, Binding should be TwoWay for validation
in MVVM
<TextBox Text="{Binding Age,Mode=TwoWay,ValidatesOnExceptions=True,NotifyOnValidationError=True}" Margin="5"></TextBox>
Set DataContext for XAML, to establish link between XAML and
ViewModel
xmlns:VM="clr-namespace:ValidationInSilverlight"
and
<UserControl.DataContext>
<VM:MainPageViewModel />
</UserControl.DataContext>
Step 5:
In the ViewModel,
Import using System.ComponentModel.DataAnnotations
name space to use ValidationException, this
will be thrown if during error.
Create property to hold value and validate before setting
value to variable, like below
private int age;
public int Age
{
get { return age; }
set
{
if (value
<= 0 || age > 200)
{
throw new
ValidationException("Age
Should be between 0 - 200");
}
age = value;
NotifyPropertyChange("Age");
}
}
Note:
Validation takes place, once the focus goes out of control
or values removed.
Sample Description:
Sample contain some more example like mandatory field, email
Project Sample:







