ViewModel validations

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:

image

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.

image

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:

image

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
  1. <ControlTemplate x:Key="validationTemplate">
  2.     <DockPanel>
  3.         <Border BorderBrush="Red" BorderThickness="2" CornerRadius="4,4,4,4"  >
  4.             <AdornedElementPlaceholder/>
  5.         </Border>
  6.         <TextBlock Foreground="Red" VerticalAlignment="Center" FontWeight="ExtraBold" Margin="4">!</TextBlock>
  7.     </DockPanel>
  8. </ControlTemplate>
  9.  
  10. <Style TargetType="TextBox">
  11.     <Setter Property="Validation.ErrorTemplate" Value="{StaticResource validationTemplate}"></Setter>
  12.     <Style.Triggers>
  13.         <Trigger Property="Validation.HasError" Value="true">
  14.             <Setter Property="TextBox.ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}"/>
  15.         </Trigger>
  16.     </Style.Triggers>
  17. </Style>

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

image

This entry was posted in ViewModel. Bookmark the permalink.

Leave a Reply

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

*