WPF风格的绑定

WPF风格的绑定,wpf,binding,styles,Wpf,Binding,Styles,我正在尝试设置一个简单的文本框,在背景中添加一些水印文本。我的代码基于中的示例 我正在尝试调整它,以便从文本框上的工具提示属性检索背景中显示的文本 目前这项工作: <TextBox ToolTip="Type a name here..."> <TextBox.Background> <VisualBrush TileMode="None" Opacity="0.4" Stretch="None" Alignm

我正在尝试设置一个简单的
文本框
,在
背景
中添加一些水印文本。我的代码基于中的示例

我正在尝试调整它,以便从
文本框
上的
工具提示
属性检索背景中显示的文本

目前这项工作:

<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>


这里有什么提示吗?

您无法以尝试的方式访问文本框,您的文本块不在文本框的可视层次结构中。因此它无法找到文本框。您可以尝试使用带水印的文本框。
对于带水印的文本框示例。

是否可以使用模板而不是样式,以便使用{Binding RelativeSource={RelativeSource TemplatedParent},Path=ToolTip}?
<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}"/>