dotnet sdk:
Hi,
I am trying to perform validation without defining a curstom validation rule
for the data bound to a text box. Instead I use the ExceptionValidationRule.
By doing the following during load and textbox lost focs event handlers i am
able to validate and mark the data as invalid or valid:
BindingExpression bexp =
txtBox.GetBindingExpression(TextBox.TextProperty);
ValidationRule rule = new ExceptionValidationRule();
ValidationError err = new ValidationError(rule, bexp);
err.ErrorContent = Resources.Val_Invalid_Length;
if (txtBox.Text.Length > width)
{
Validation.MarkInvalid(bexp, err);
}
else
{
Validation.ClearInvalid(bexp);
}
I have defined a Style which gets triggered when HasError is true. So I am
able to see the red border around the textbox but do not see the exclamation
mark defined on the Validation.ErrorTemplate. But if the textbox is in focus
and has lost focus the control template gets fired and displays the read
rectangle with the exclamation mark. Any idea how i could display the
controltemplate when the binding data is loaded and marked invalid the first
time the ui is loaded. Following is what I am doing in the xaml code to set
up the style template.
<Style x:Key="textBoxStyle" TargetType ="{x:Type TextBox}">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="BorderBrush" Value="Red"/>
<Setter Property="BorderThickness" Value="1.5"/>
<Setter Property="ToolTip" Value="{Binding
RelativeSource={RelativeSource Self},
Path=(Validation.Errors)[0].ErrorContent}">
</Setter>
</Trigger>
</Style.Triggers>
<Setter Property="Height" Value="20"/>
<Setter Property="Width" Value="150"/>
<!--Setter Property="HorizontalAlignment" Value="Left"/-->
<Setter Property="Grid.Column" Value="1"/>
<Setter Property ="Margin" Value="5"/>
<Setter Property="Validation.ErrorTemplate">
<Setter.Value>
<ControlTemplate>
<DockPanel HorizontalAlignment="Right"
VerticalAlignment="Top" Margin="10,0,5,5">
<TextBlock DockPanel.Dock="Right"
Canvas.Bottom=".5" Canvas.Left=".5" Canvas.Right=".5" Canvas.Top=".5"
Background="Red" Width="15" TextAlignment="Center" Foreground="Black"
FontSize="15">!</TextBlock>
<AdornedElementPlaceholder
DockPanel.Dock="Top"/>
</DockPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Here is the xaml code for the textbox incorporated in the textblock.
<TextBlock Margin="10,15,0,5">Last Name:
<TextBox Name="lastNameTextBox" Margin="5,15,0,0" Width="110"
Style="{StaticResource textBoxStyle}"
Validation.ErrorTemplate="{StaticResource
validateErrorTemplate}"
local:FieldDefExpression.ID="TestField-A">
<TextBox.Text>
<Binding Path="LastName"
UpdateSourceTrigger="PropertyChanged" >
<Binding.ValidationRules>
<ExceptionValidationRule/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
</TextBlock>
Thanks.
Regards,