2010-03-30 96 views
8

我正试图在Background中设置一个简单的TextBox以及一些水印文本。我的代码基于Philip Patrick's blog的示例。WPF绑定风格

我试图调整它,以便在TextBox上的ToolTip属性中检索显示在背景中的文本。

目前这个工程:

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

,显示在TextBoxBackgroundToolTip文本。

但是,如果我移动代码的一部分出来的资源风格的结合不再获得来自TextBoxToolTip信息:

<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}"/> 

这里

任何提示吗?

+1

你能使用模板,而不是一个风格的,所以你可以使用{绑定的RelativeSource = {的RelativeSource TemplatedParent},路径=工具提示}? – 2010-03-30 16:57:24

回答

1

您不能以您尝试的方式访问TextBox,您的TextBlock不在TextBox的可视层次结构中。所以它无法找到文本框。您可以尝试使用水印文本框。 Check this水印文本框样本。

1

我刚刚有一个相同的问题,最终通过绑定到工具提示的PlacementTarget来解决它。答案就在这里详细link text

杰里米