Validation Messages – MVVM Approach

What follows is a simple way to carry along a collection of Validation Messages in your ViewModel, and then bind them to the UI at runtime.

 

The first step is to create an ObservableCollection of validation messages on the ViewModel class.  This is going to hold the messages at runtime.

public ObservableCollection<TLValidationMessage> ValidationMessages
{
    get { return _validationMessages; }
    set
    {
        if (_validationMessages == value) return;
        _validationMessages = value;
        NotifyPropertyChanged("ValidationMessages");
    }
}

We’ll also need to define what TLValidationMessages are.  They’re simply a Message string and a Severity Level, which could be used to change the styling at runtime based on the importance of the message.

public enum SeverityLevel
{
    Error,
    Warning,
    Info
}
/// <summary>
/// </summary>
public class TLValidationMessage
{

    /// <summary>
    /// Message to show the user
    /// </summary>
    public string Message { get; set; }

    /// <summary>
    /// This helps change the styling, based on the severity level.
    /// </summary>
    public SeverityLevel Level { get; set; }
}

 

Next we’ll create a little helper method on the ViewModel that will add new messages to our collection:

/// <summary>
/// Adds a validation message to the bottom of the UI, with the appropriate styling.
/// </summary>
/// <param name="level"></param>
/// <param name="message"></param>
public void AddValidationMessage(SeverityLevel level, string message)
{
    if (ValidationMessages == null) ValidationMessages = new ObservableCollection<TLValidationMessage>();

    ValidationMessages.Add(new TLValidationMessage
                               {
                                   Level = level,
                                   Message = message
                               });
    NotifyPropertyChanged("ValidationMessages");
}

Now we’ll need to call this helper method anywhere a validation error occurs (typically in other methods in the ViewModel itself.

if (someitem.SomeCollection == null)
{
    AddValidationMessage(SeverityLevel.Error, "There are no items.");
    return;
}

Turning our attention to the xaml, we’ll add an ItemsControl inside a Border, which will display the messages:

<Border x:Name="Validation" Grid.Column="0" BorderThickness="1" Grid.Row="3" Grid.ColumnSpan="2" HorizontalAlignment="Center">
    <ItemsControl ItemsSource="{Binding ValidationMessages, Mode=OneWay}" BorderBrush="{x:Null}" ItemTemplate="{StaticResource ValidationMessageTemplate}" Foreground="#FFFF0202"/>
</Border>

You may have noticed the template was set to ItemTemplate="{StaticResource ValidationMessageTemplate}"  Here is the DataTemplate to control the display.

<DataTemplate x:Key="ValidationMessageTemplate">
    <Grid>
        <StackPanel Orientation="Horizontal" d:LayoutOverrides="Height">
            <TextBlock Text="{Binding Message}"/>
        </StackPanel>
    </Grid>
</DataTemplate>

As long as you’ve set the DataContext of the parent control, and your binding lines up, this will display the Validation Messages as they occur.

Hope this helps!

// Dave

This entry was posted in Development and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *