Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Binding in Style

I'm trying to set together a simple TextBox with some watermark text in the Background. My code is based on the example from Philip Patrick's blog.

I'm trying to tweak it so that the text displayed in the background is retrieved from the ToolTip property on the TextBox.

Currently this works:

<TextBox ToolTip="Type a name here...">
            <TextBox.Background>
                <VisualBrush TileMode="None" Opacity="0.4" Stretch="None" AlignmentX="Left">
                    <VisualBrush.Visual>
                        <TextBlock FontStyle="Italic" Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TextBox}}, Path=ToolTip}"/>
                    </VisualBrush.Visual>
                </VisualBrush>
            </TextBox.Background>
        </TextBox>

That displays the ToolTip text in the Background of the TextBox.

But if I move part of the code out to a Resource Style the binding no longer gets the ToolTip info from the TextBox:

<Grid>
    <Grid.Resources>
        <Style x:Key="WatermarkBackground" TargetType="{x:Type TextBox}">
            <Setter Property="Background">
                <Setter.Value>
                    <VisualBrush TileMode="None" Opacity="0.4" Stretch="None" AlignmentX="Left">
                        <VisualBrush.Visual>
                            <TextBlock FontStyle="Italic" Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TextBox}}, Path=ToolTip}"/>
                        </VisualBrush.Visual>
                    </VisualBrush>
                </Setter.Value>
            </Setter>
        </Style>
    </Grid.Resources>

    <TextBox ToolTip="Type your name here..." Style="{StaticResource WatermarkBackground}"/>

Any tips here?

like image 520
Frode Lillerud Avatar asked Mar 30 '10 14:03

Frode Lillerud


1 Answers

You cann't access TextBox the way you are trying, your TextBlock is not in the visual hierarchy of your TextBox. So it is not able to find the TextBox. You can try with Watermarked TextBox. Check this for a Sample of Watermarked TextBox.

like image 192
viky Avatar answered Oct 25 '22 09:10

viky