如何从wpf中的样式绑定到标记?

时间:2012-11-11 20:07:10

标签: wpf binding

我正在实施一个搜索文本框;你可以帮我绑定TextBox.Tag吗?

风格

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

用法

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

如何让绑定工作?

1 个答案:

答案 0 :(得分:2)

这篇文章与您的文章非常相似: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" />