In previous post about validation in Silverlight, I explained the How binding is used to validate data ? .
Here i am going to explain how to validate Textbox ( Any control that has validation states group).
There are three validation states. 1. Valid 2. InvalidFocused 3. InvalidUnfocused. Now use VisualStateManager to change the state of control. Here is common method.
public void SetState(Control c, string message,string state)
{
if (state == "Invalid")
{
if (c.Focus())
VisualStateManager.GoToState(c, "InvalidFocused", false);
else
VisualStateManager.GoToState(c, "InvalidUnfocused", false); ToolTip tp = ((Grid)VisualTreeHelper.GetChild(c, 0)).FindName("validationTooltip") as ToolTip;
tp.DataContext = message;
tp.Template = LayoutRoot.Resources["ValidationToolTipTemplate"] as ControlTemplate;
}
else
{
VisualStateManager.GoToState(c, "Valid", false);
}
}
In XAML Page you have to specify control template.
<ControlTemplate x:Key="ValidationToolTipTemplate">
<Grid x:Name="Root" >
<Border Margin="4,4,-4,-4" Background="#152A2E31" CornerRadius="4"/>
<Border Margin="3,3,-3,-3" Background="#252A2E31" CornerRadius="4"/>
<Border Margin="2,2,-2,-2" Background="#352A2E31" CornerRadius="4"/>
<Border Margin="1,1,-1,-1" Background="#452A2E31" CornerRadius="4"/>
<Border Background="#FFDC000C" CornerRadius="4"/>
<Border CornerRadius="4">
<Border.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#66FFFFFF"/>
<GradientStop Color="#66000000" Offset="1"/>
<GradientStop Color="#00E5E5E5" Offset="0.1"/>
<GradientStop Color="#00161616" Offset="0.9"/>
</LinearGradientBrush>
</Border.Background>
<TextBlock Margin="8,3,8,4" MaxWidth="250" UseLayoutRounding="false" Foreground="White" Text="{Binding}" TextWrapping="Wrap"/>
</Border>
</Grid>
</ControlTemplate>
This control template is used for validation tooltip.
Control like Textbox,listbox ,combobox,checkbox has validation states so you can use this method.
Example:
if(txtFirstName.Text == “”)
{
SetState(txtFirstName , “Invalid”, “Please enter first name”);
}
Let me know you comment on this.