WPF RelativeSource FindAncestor doesn't work outside of the Control.Resources context?

Posted by sker on Stack Overflow See other posts from Stack Overflow or by sker
Published on 2010-04-23T04:49:24Z Indexed on 2010/04/23 4:53 UTC
Read the original article Hit count: 807

I have this VisualBrush resource I took from some site and I apply it with triggers to a TextBox.

<VisualBrush x:Key="HelpBrush" TileMode="None" Opacity="0.4" Stretch="None" AlignmentX="Left">
    <VisualBrush.Visual>
        <TextBlock FontStyle="Italic"
                   Text="{Binding Path=Tag, RelativeSource={RelativeSource AncestorType={x:Type Control}, AncestorLevel=1}}"/>
    </VisualBrush.Visual>
</VisualBrush>

<Style x:Key="DefaultText" TargetType="TextBox">
    <Style.Triggers>
        <Trigger Property="Text" Value="{x:Null}">
            <Setter Property="Background" Value="{StaticResource HelpBrush}"/>
        </Trigger>
        <Trigger Property="Text" Value="">
            <Setter Property="Background" Value="{StaticResource HelpBrush}"/>
        </Trigger>
    </Style.Triggers>
</Style>

If I place both the VisualBrush and the Style inside the TextBox.Resources tag in XAML, it works fine. But if I take it out and place it in the Window.Resources or a merged dictionary, it stops working.

The problem is the Binding, it doesn't find the ancestor TextBox for some reason. I already tried removing AncestorLevel and using AncestorType={x:Type TextBox} - it doesn't work.

Any ideas?

© Stack Overflow or respective owner

Related posts about wpf

Related posts about xaml