0
votes

I want to create a Trigger to be applied to all TextBox on Validation.HasError to show the Validation.Error in a custom ToolTip.

<Style TargetType="{x:Type TextBox}">
    <Style.Triggers>
        <Trigger Property="Validation.HasError" Value="True">
        <Setter Property="Background" Value="Red"/>
        <Setter Property="ToolTip">
            <Setter.Value>
                <StackPanel>
                    <TextBlock Text="{Binding RelativeSource={RelativeSource XXX}, Path=(Validation.Error)[0].ErrorContent}"/>
                </StackPanel>
            </Setter.Value>
        </Setter>
        </Trigger>
    </Style.Triggers>
</Style>

What should I put in the XXX?

My problem is that I don't really understand how RelativeSource works in this context and I can't get the correct code for binding to the TextBox.

I am guessing Self would refer to the TextBlock and FindAncestor x:Type TextBox will fail becuase it will traverse from TextBlock > StackPanel > Setter.Value > Setter > etc.. instead.

How can I refer to the Style Target instead?

1

1 Answers

2
votes

Since ToolTip is not part of the visual tree, it's a bit cumbersome to get the behavior you want.

You can use its PlacementTarget property to find the element it is attached to, and set its DataContext to that element. In your case that will be a TextBox.

Now you can bind directly to the Validation.Errors property, and it will find the validation errors on a given TextBox.

You can use the following code to get it working:

<Window.Resources>
    <ToolTip x:Key="errorTooltip" 
             DataContext="{Binding PlacementTarget,
                                   RelativeSource={RelativeSource Self}}">
        <StackPanel>
            <TextBlock Text="{Binding (Validation.Errors)[0].ErrorContent}" />
        </StackPanel>
    </ToolTip>

    <Style TargetType="{x:Type TextBox}">
        <Style.Triggers>
            <Trigger Property="Validation.HasError" Value="True">
                <Setter Property="Background" Value="Red"/>
                <Setter Property="ToolTip" Value="{StaticResource errorTooltip}" />
            </Trigger>
        </Style.Triggers>
    </Style>
</Window.Resources>