2012-01-27 62 views
2

我有一個在App.xaml中定義的默認TextBlock樣式,這似乎也影響ComboBox項目的文本顏色。現在,我該如何顯式設置在我的主窗口中定義的組合框的文本顏色? (我想保持默認的風格,但有組合框的文本顏色,比如藍色,而不是紅色...)覆蓋組合框中默認的TextBlock樣式

的App.xaml

<Application x:Class="WpfApplication1.App" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     StartupUri="MainWindow.xaml"> 
<Application.Resources> 
    <Style TargetType="{x:Type TextBlock}"> 
     <Setter Property="Foreground" Value="Red" /> 
    </Style> 
</Application.Resources> 

MainWindow.xaml

<Window x:Class="WpfApplication1.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="MainWindow"> 
<Grid> 
    <ComboBox Name="comboBox1" SelectedIndex="0" HorizontalAlignment="Left" VerticalAlignment="Top"> 
     <ComboBoxItem Content = "Item1"/> 
     <ComboBoxItem Content = "Item2"/> 
     <ComboBoxItem Content = "Item3"/> 
    </ComboBox> 
</Grid> 

事情我已經嘗試:

  1. 集Combobox.Foreground
  2. 集TextElement.Foreground
  3. 集TextBlock.Foreground
  4. 定義在ComboBox.Resources另一個隱含的TextBlock風格
  5. 定義Grid.Resources中的另一個隱式TextBlock樣式
  6. 在Window.Resources中定義另一個隱式TextBlock樣式

回答

3

大多數隱含TextBlock的樣式將停止在控制邊界,除非你把它們放在Application.Resources

例如,將你的風格在Window.Resources將使它適用於所有<TextBlock>對象,但不包括其他控制內的文本模板如ComboBoxButton

我會建議將您的風格融入Window.Resources,然後你的造型組合框的項目有任何你想要的前景色。

<ComboBox.Resources> 
    <Style TargetType="{x:Type ComboBoxItem}"> 
     <Setter Property="Foreground" Value="Blue" /> 
    </Style> 
</ComboBox.Resources> 

如果你想保持它在Application.Resources,那麼我懷疑你需要跟蹤什麼x:Static刷鍵用於設置TextBlock.Text顏色和覆蓋在你的ComboBox.Resources

+0

我嘗試在組合框資源中添加另一個TextBlock樣式。不幸的是,它沒有任何效果。 – 2012-01-27 15:08:20

+0

我編輯的問題,包括我已經嘗試過的一些事情 – 2012-01-27 15:12:11

+0

@ErenErsonmez看到我編輯的答案。我沒有注意到你在'Application.Resources'中有自己的樣式,而沒有'Window.Resources' – Rachel 2012-01-27 15:24:50

1

你必須使用觸發器在ComboBoxItem

<Style TargetType="{x:Type ComboBoxItem}"> 
    <Style.Triggers> 
     <Trigger Property="ComboBoxItem.IsMouseOver" Value="true"> 
      <Setter Property="Foreground" Value="Red"/> 
     </Trigger> 

     <Trigger Property="ComboBoxItem.IsMouseOver" Value="false"> 
      <Setter Property="Foreground" Value="Blue"/> 
     </Trigger> 
    </Style.Triggers> 
</Style> 

如果你想保持它的靜態然後

<Style TargetType="{x:Type ComboBoxItem}"> 
    <Setter Property="Foreground" Value="Blue"/> 
</Style> 
+1

,當隱式樣式在App.xaml中時,這不起作用。 – 2012-01-27 15:37:32

+0

然後,您必須使用x:Key,覆蓋默認的ComboBox模板,在樣式中應用該模板,並將該樣式應用於ComboBox – MyKuLLSKI 2012-01-27 15:50:02