WPF Validation ErrorTemplate display trouble

1.1k Views Asked by At

I have a simple WPF Grid with two rows and two columns. The second column contains TextBox-es which are bound to some view model properties. I need to customize these TextBoxes validation ErrorTemplates to display validation error just above the problem box.

Following code

<Style TargetType="Control" x:Key="ValidationControlStyle">
  <Setter Property="Validation.ErrorTemplate">
    <Setter.Value>
      <ControlTemplate>
        <StackPanel>
          <TextBlock Foreground="Red"
                     Text="{Binding ElementName=ErrorAdorner, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}"/>
          <AdornedElementPlaceholder x:Name="ErrorAdorner"/>
        </StackPanel>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

gives very ugly result when error message visually overlaps above row (see picture below)

enter image description here

How can I place validation error just above the problem field (Grid row should increase its height)?

1

There are 1 best solutions below

0
On BEST ANSWER

Maybe place the Validation TextBlock in the main UI Layer, and set its Visibility using a DataTrigger based off of the Validation.HasError?

Binding syntax should be something like this :

<Style x:Key="ErrorTextBlock" TargetType="{x:Type TextBlock}">
    <Setter Property="Visibility" Value="False" />
    <Setter Property="Foreground" Value="Red" />
    <DataTrigger Binding="{Binding ElementName=MyTextBox, Path=Validation.HasError" Value="True">
        <Setter Property="Visibility" Value="True"/>
    </DataTrigger>
</Style>

I'm sure there's some way to make it generic too if you want :)