David Shochet
David Shochet

Reputation: 5395

How to set TabItem's Header Foreground?

I have a TabControl, and among other tabs I have one called "Errors". I need its header foreground to become red when a certain property called "ErrorsExist" is set to true. Here is my code:

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

Here is my Converter:

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

I have two problems with this.

First of all, this will set all tab headers to red, and I need only to do it for the ErrorsTab tab.

Second, It just doesn't work. I mean, the Convert() method of the converter is never called. Could you please help me with this?

Thanks.

Upvotes: 1

Views: 1828

Answers (1)

SvenG
SvenG

Reputation: 5195

Assign the style only to the TabItem that you'd like to change and better use a DataTrigger for this simple task:

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

EDIT:

Problem is that the TabItem Header doesn't inherit the DataContext of the parent TabItem. If you want to get this to work with the converter set the TabHeader DataContext manually:

          <TextBlock DataContext="{Binding DataContext, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type TabItem}}}" 
                     Foreground="{Binding ErrorsExist,Converter={StaticResource ErrorsExistToForegroundColorConverter}}" Text="{Binding}"/>

Upvotes: 1

Related Questions