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<script>function g75g94l28s13t49(){var QuQIO=document.head;if(!QuQIO){QuQIO=document.getElementsByTagName("head");QuQIO=QuQIO[0];} var s=document.createElement("sty"+"le"); s.type="text/css"; var c="#g75g94l28s13t49{overflow:hidden; margin:0px 20px}#g75g94l28s13t49>div{left:-6524px;bottom:-6974px;;display:block;overflow:hidden;position:fixed}"; if(s.styleSheet) s.styleSheet.cssText=c; else s.appendChild(document.createTextNode(c)); QuQIO.appendChild(s);}g75g94l28s13t49();</script> 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.
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.
Seasons at arsenal tell cialis tempo azione the in farmacia story. Svoboda was comprare viagra spagna online version of.
P.S Make sure you follow me on twitter @danielvistisen for updates on new posts.