WPF绑定风格

Fro*_*rud 8 wpf binding styles

我正在尝试将一个简单的TextBox水印文本放在一起Background.我的代码基于Philip Patrick博客的示例.

我正在尝试调整它,以便从后面的ToolTip属性中检索背景中显示的文本TextBox.

目前这有效:

<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>
Run Code Online (Sandbox Code Playgroud)

这显示ToolTip在文本BackgroundTextBox.

但是,如果我将部分代码移到资源样式,则绑定不再ToolTip从以下内容获取信息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}"/>
Run Code Online (Sandbox Code Playgroud)

有什么提示吗?

vik*_*iky 1

您无法按照您尝试的方式访问 TextBox,您的 TextBlock 不在 TextBox 的视觉层次结构中。所以它无法找到TextBox。您可以尝试使用带水印的文本框。 检查此以获取带水印的文本框示例。