3

I'm implementing a search textbox; could you please help me with binding to TextBox.Tag?

Style

<Style x:Key="SearchTextBox" TargetType="{x:Type TextBox}">
      <Style.Resources>
       <VisualBrush x:Key="CueBannerBrush" AlignmentX="Left" AlignmentY="Center" Stretch="None">
          <VisualBrush.Visual>
            <Label Content="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Tag}" Foreground="{StaticResource SearchTextBox.Foreground}" FontSize="{StaticResource SearchTextBox.FontSize}"/>
          </VisualBrush.Visual>
        </VisualBrush>
      </Style.Resources>
      <Setter Property="FontSize" Value="{StaticResource SearchTextBox.FontSize}" />
      <Setter Property="Foreground" Value="{StaticResource SearchTextBox.TextForeground}" />
      <Setter Property="MinWidth" Value="200" />
          <Style.Triggers>
            <Trigger Property="Text" Value="{x:Static sys:String.Empty}">
              <Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
            </Trigger>
            <Trigger Property="Text" Value="{x:Null}">
              <Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
            </Trigger>
            <Trigger Property="IsKeyboardFocused" Value="True">
              <Setter Property="Background" Value="White" />
            </Trigger>
          </Style.Triggers>
    </Style>

Usage

<TextBox Style="{StaticResource SearchTextBox}" Tag="Search templates" />

How can I get the binding to work?

4

1 回答 1

3

这篇文章与你的非常相似:WPF Bind to parent property from within nested element using style

虽然,它并没有真正提供代码示例,所以这里有一些 xaml 可以用作当前方法的替代方法。

<Style x:Key="SearchTextBox" BasedOn="{StaticResource {x:Type TextBox}}" TargetType="{x:Type TextBox}">
  <Style.Setters>
    <Setter Property="Tag" Value=""/>
    <Setter Property="Template">
      <Setter.Value>
        <ControlTemplate TargetType="{x:Type TextBox}">
          <Grid>
            <ScrollViewer x:Name="PART_ContentHost" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
            <TextBlock x:Name="textBlock" Opacity="0.345" Text="{TemplateBinding Tag}" TextWrapping="Wrap" Visibility="Hidden" />
          </Grid>
          <ControlTemplate.Triggers>
            <MultiTrigger>
              <MultiTrigger.Conditions>
                <Condition Property="IsFocused" Value="False" />
                <Condition Property="Text" Value="" />
              </MultiTrigger.Conditions>
              <Setter Property="Visibility" TargetName="textBlock" Value="Visible" />
            </MultiTrigger>
          </ControlTemplate.Triggers>
        </ControlTemplate>
      </Setter.Value>
    </Setter>
  </Style.Setters>
</Style>

而且你仍然会用你已经拥有的方式编写你的文本框代码:

<TextBox Style="{StaticResource SearchTextBox}" Tag="Search templates" />
于 2012-11-11T21:27:44.257 回答