views:

218

answers:

2

Hi, 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 get 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?

+1  A: 

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.

viky
A: 

I just had an identical problem and ended up solving it by binding to the PlacementTarget of the ToolTip. The answer is in detail here link text

Jeremy

Jeremy Holt