Supporting INotifyDataErrorInfo in Windows Phone 8.1 Silverlight

Introduction

In this post, I am going to show how to add validation to Windows Phone. As I mentioned in a previous post Windows Phone supports INotifyDataErrorInfo to some degree. The goal here is to add a red border to a Textbox when its text is invalid. Note that this approach is useful for all controls not only textboxes.

VisualStateGroup

The key to this is to create an additional visual state group.

<VisualStateGroup
    x:Name="ValidationStates">
    <VisualState
        x:Name="InvalidFocused" />
    <VisualState
        x:Name="InvalidUnfocused" />
    <VisualState
        x:Name="Valid" />
</VisualStateGroup>

When a control is invalid depending on whether it has focus or not it sets the following states.

  • InvalidFocused
    • When the control is invalid with focus.
  • InvalidUnfocused
    • When the control is invalid without focus

Valid is of course set when the bound value is valid.

ControlTemplate

By default, no control has any of these states in their control template. For the textbox, I am just going to edit copy of its original template.

After creating a copy, I placed the new visual state group inside the template.

TextBoxStyle Image

I chose to create storyboards with blend. Setting the MainBorder’s border brush to red when in InvalidFocused and InvalidInfocused state. The result looks like this.

 <VisualStateGroup
     x:Name="ValidationStates">
     <VisualState
         x:Name="InvalidFocused">
         <Storyboard>
             <ColorAnimation
                 Duration="0"
                 To="Red"
                 Storyboard.TargetProperty="(Border.BorderBrush).(SolidColorBrush.Color)"
                 Storyboard.TargetName="MainBorder"
                 d:IsOptimized="True" />
         </Storyboard>
     </VisualState>
     <VisualState
         x:Name="InvalidUnfocused">
         <Storyboard>
             <ColorAnimation
                 Duration="0"
                 To="Red"
                 Storyboard.TargetProperty="(Border.BorderBrush).(SolidColorBrush.Color)"
                 Storyboard.TargetName="MainBorder"
                 d:IsOptimized="True" />
         </Storyboard>
     </VisualState>
     <VisualState
         x:Name="Valid" />
 </VisualStateGroup>

Now all I need to do is set my new style on the TextBox

<TextBox
    Style="{StaticResource TextBoxStyle}"
    Text="{Binding FirstName, Mode=TwoWay}" />

To “turn off” the validation set ValidatesOnNotifyDataErrors to false.

<TextBox
    Style="{StaticResource TextBoxStyle}"
    Text="{Binding FirstName, Mode=TwoWay, ValidatesOnNotifyDataErrors=False}" />

You can download the demo project here.

P.S Make sure you follow me on twitter @danielvistisen for updates on new posts.

Supporting INotifyDataErrorInfo in Windows Phone 8.1 Silverlight