Run validation in WPF only when management is enabled

I apply binding verification to multiple WPF elements in .NET 4.0. My controls are currently blushing and displaying a small warning message when they are not running a specific set of ValidationRules. The problem is that they still do not perform their respective checks, even though they are disabled. This can be misleading to the end user, and therefore I would just like the check to be performed if the controls are enabled. I'm not quite sure how to implement this functionality.

I test through the Binding.ValidationRule, which connects through a specific validation class.

EDIT: The reason the errors are displayed is because my check checks if the field is empty. When the form loads, the fields are empty and do not allow validation, even if they are disabled.

+4
source share
2 answers

Let me answer my own question:

In my research there is no way to do this. The best way to not display a validation error when a control is disabled is to create a Validation.ErrorTemplate template, which is special when the control has failed validation and is disabled. I used this method to solve this problem.

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> 

The red error border will not be displayed when validation fails and the control is disabled.

+2
source

Another solution is to pull the IsEnabled value from the decorated element through the AdornedElement property of your AdornedElementPlaceholder . In the example below, I use IsEnabled="{Binding ElementName=customAdorner, Path=AdornedElement.IsEnabled}" . Then you can disable IsEnabled as usual.

  <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 advantage is that this approach simplifies layout support if it is not an error, if you have other text blocks, etc. in ErrorTemplate .

0
source

Source: https://habr.com/ru/post/1488724/


All Articles