Reputation: 1160
I am applying binding validation to a few WPF controls in .NET 4.0. Currently, my controls turn red and display a little warning message when they fail a certain set of ValidationRules. The problem is that, they still fail their respective validations even though they are disabled. This could be misleading to the end user and therefore I would only like validation to run if the controls are enabled. I am not exactly sure how to implement this functionality.
I validate through Binding.ValidationRule which connects through a specific validation class.
EDIT: The reason that the errors are showing is because my validation checks if the field is empty. When the form loads, the fields are empty and fail the validation even though they are disabled.
Upvotes: 4
Views: 2658
Reputation: 368
Another solution is to pull the value of IsEnabled
from the adorned element via the AdornedElement
property of your AdornedElementPlaceholder
. In the example below I use IsEnabled="{Binding ElementName=customAdorner, Path=AdornedElement.IsEnabled}"
. Then you can trigger off IsEnabled
like normal.
<Style x:Key="TextBoxValidationStyle" TargetType="{x:Type TextBox}">
<Setter Property="Validation.ErrorTemplate">
<Setter.Value>
<ControlTemplate>
<DockPanel IsEnabled="{Binding ElementName=customAdorner, Path=AdornedElement.IsEnabled}">
<AdornedElementPlaceholder x:Name="customAdorner">
<Border x:Name="Border" BorderThickness="1">
<Border.Style>
<Style TargetType="Border">
<Style.Triggers>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="BorderBrush" Value="Transparent" />
</Trigger>
<Trigger Property="IsEnabled" Value="True">
<Setter Property="BorderBrush" Value="Red" />
</Trigger>
</Style.Triggers>
</Style>
</Border.Style>
</Border>
</AdornedElementPlaceholder>
</DockPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
The benefit is that this approach makes it easier to maintain the layout when not in error if you've got other text blocks etc in your ErrorTemplate
.
Upvotes: 0
Reputation: 1160
Let me answer my own question:
There is really no way to this from my research. The best way to not display the validation error when the control is disabled is to create a Validation.ErrorTemplate that is special to when the control fails the validation and is disabled. I used this technique to solve this issue.
Something along the lines of:
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Validation.ErrorTemplate">
<Setter.Value>
<ControlTemplate>
<DockPanel>
<Border BorderBrush="Gray" BorderThickness="0">
<AdornedElementPlaceholder/>
</Border>
</DockPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Trigger>
Will not display the red error border when the validation fails and the control is disabled.
Upvotes: 2