2012-04-04 41 views
1

我有一個TabControl,並在其他選項卡中我有一個名爲「錯誤」。當某個名爲「ErrorsExist」的屬性設置爲true時,我需要將其頭部前景變爲紅色。這裏是我的代碼:如何設置TabItem的標題前景?

  <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()方法永遠不會被調用。你能幫我解決這個問題嗎?

謝謝。

回答

1

指定的樣式只有你想改變和更好的使用DataTrigger這個簡單的任務的TabItem:

<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的標題沒有按不繼承父TabItem的DataContext。 如果你想獲得這與手動設置的TabHeader DataContext的轉換工作:

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

非常感謝你,它的工作。我只是想知道爲什麼它不適用於轉換器... – 2012-04-04 13:56:18

+0

不客氣。已編輯帖子,並添加了一個基於轉換器的解決方案... – SvenG 2012-04-04 15:11:42

+0

奇怪的是,我沒有看到它... – 2012-04-04 15:14:47