Log in

ViewModel validations

From MDrivenWiki

Validations are there to enforce a set of rules that apply to a specific use case. A use case is implemented by a ViewModel, so the ViewModel needs Validations.

This is how you add them in the ViewModelEditor:

Valid -1.png

You will get a new row in the Validations list. Fill in the rule name, the expression that should evaluate to true when the rule is fulfilled, and false when data breaks the rule. You also provide a text with the error message you want to show.

The context of the rule is the context of the Main ViewModelClass; this means that you reach variables etc.

Valid -2.png

You can have as many rules as you need.

The rule state (true of false) can then be displayed by one or multiple columns. You right click a ViewModelColumn and check the correct rule to make an association between the two:

Valid -4.png

Once the association is made and a rule break is discovered in runtime a standard WPF ValidationError will occur. How this ValidationError is displayed is defined by styles.

In WECPOF I added a default style – override it if you need – that brings up a tool tip, draws an exclamation mark behind the offending control and draws a red border around the value.

The default style is defined like this:

Code Snippet

<ControlTemplate x:Key="validationTemplate">
    <Border BorderBrush="Red" BorderThickness="2" CornerRadius="4,4,4,4"  >
    <TextBlock Foreground="Red" VerticalAlignment="Center" FontWeight="ExtraBold" Margin="4">!</TextBlock>

<Style TargetType="TextBox">
  <Setter Property="Validation.ErrorTemplate" Value="{StaticResource validationTemplate}">
    <Trigger Property="Validation.HasError" Value="true">
      <Setter Property="TextBox.ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}"/>

And when the rule is broken the it looks like this in runtime:

Valid -5.png