ControlTemplate and validation - How to position items?

1.4k views Asked by At

I created ControlTemplate which is shown if there are validation error on my textbox. My controltemplate looks like that

<ControlTemplate x:Key="TextBoxErrorTemplate">
  <TextBlock  Foreground="Orange" FontSize="12pt">Field can't be empty</TextBlock>
</ControlTemplate>

However if validation errors occure textBlock appears on textBox - and the user can't enter proper value. Is there any way to set the position of TextBlock - the one which shows error info?

1

There are 1 answers

2
brunnerh On

ErrorTemplates are for adorning the control and not for changing its internal properties, to do this you should use a style with the respective trigger:

            <Style TargetType="TextBox">
                <Style.Triggers>
                    <Trigger Property="Validation.HasError" Value="True">
                        <Setter Property="Foreground" Value="Orange"/>
                        <Setter Property="FontSize" Value="12"/>
                    </Trigger>
                </Style.Triggers>
            </Style>

If you want to display some text you could use a template like this:

    <ControlTemplate x:Key="TextBoxErrorTemplate">
        <StackPanel Orientation="Horizontal">
            <AdornedElementPlaceholder/>
            <TextBlock  Foreground="Orange" FontSize="12pt">Field can't be empty</TextBlock>
        </StackPanel>
    </ControlTemplate>

The TextBlock will be displayed on the right of the TextBox.

If you just want to show error messages i'd suggest you set the tooltip of the TextBox and bind it to the validation errors.