1

我有一个 TabControl,在其他选项卡中,我有一个名为“错误”的选项卡。当某个名为“ErrorsExist”的属性设置为 true 时,我需要它的标题前景变为红色。这是我的代码:

           <TabControl >
            <TabControl.Resources>
                <conv:ErrorsExistToForegroundColorConverter x:Key="ErrorsExistToForegroundColorConverter"/>

                <Style TargetType="{x:Type TabItem}">
                    <Setter Property="HeaderTemplate">
                        <Setter.Value>
                            <DataTemplate>
                                <TextBlock Foreground="{Binding  Path=ErrorsExist, Converter={StaticResource ErrorsExistToForegroundColorConverter}}" Text="{Binding}"/>
                            </DataTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </TabControl.Resources>

            <TabItem x:Name="ErrorsTab" Header="Errors">

这是我的转换器:

    public class ErrorsExistToForegroundColorConverter: IValueConverter
{

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
       switch ((bool)value)
       {
          case true:
             return Brushes.Red;
          case false:
             return Brushes.Black;
          default:
             return Binding.DoNothing;
       }
    }

我有两个问题。

首先,这会将所有选项卡标题设置为红色,我只需要为 ErrorsTab 选项卡执行此操作。

其次,它只是不起作用。我的意思是,转换器的 Convert() 方法永远不会被调用。你能帮我解决这个问题吗?

谢谢。

4

1 回答 1

1

仅将样式分配给您想要更改的 TabItem 并更好地使用 DataTrigger 来完成这个简单的任务:

<TabItem x:Name="ErrorsTab" Header="Errors">
    <TabItem.Style>
      <Style TargetType="{x:Type TabItem}">
        <Style.Triggers>
          <DataTrigger Binding="{Binding ErrorsExist}" Value="True">
              <Setter Property="Foreground" Value="Red"/>
          </DataTrigger>
         </Style.Triggers>
       </Style>
    </TabItem.Style>
  </TabItem>

编辑:

问题是 TabItem Header 没有继承父 TabItem 的 DataContext。如果您想让它与转换器一起使用,请手动设置 TabHeader DataContext:

          <TextBlock DataContext="{Binding DataContext, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type TabItem}}}" 
                     Foreground="{Binding ErrorsExist,Converter={StaticResource ErrorsExistToForegroundColorConverter}}" Text="{Binding}"/>
于 2012-04-04T13:07:30.280 回答