2010-02-10 168 views
1

突然顯示黑色文本的突出顯示黑色文本時,突出顯示的文本應爲白色時,我遇到了突出顯示問題。C#WPF - 突出顯示文本顏色問題的組合框突出顯示

我有ComboBox的例子,其中的內容是一個字符串使用ComboBoxItems。這些情況下的組合框的行爲與預期相同 - 當組合框下拉時,如果突出顯示一個項目,它會在藍色背景上顯示白色文本。

但是我有一個ComboBox的例子,其中每個ComboBoxItem的內容都是一個網格(網格包含2列 - 第一個包含文本,第二個線 - 它是一個線寬度組合框)。在這種情況下,當組合框下拉時,如果突出顯示一個項目,它會在藍色背景上顯示黑色文本而不是白色文本。注意:即使我刪除行部分,因此只有一列包含文本,我仍然看到問題。

最近我來解決這個問題是添加資源到SystemColors.HighlightBrushKey和SystemColors.HighlightTextBrushKey的組合框中,我設置畫筆的顏色。但是,SystemColors.HighlightBrushKey確實會更改高亮的背面顏色(但這不是我想要的),並且當我嘗試使用SystemColors.HighlightTextBrushKey時,我認爲它會更改高亮顯示的項目的文本顏色,不會改變)。

實施例編輯的代碼:

var combo = new ComboBox(); 

Func<double, object> build = d => 
{ 
    var grid = new Grid(); 
    grid.ColumnDefinitions.Add(new ColumnDefinition {Width = GridLength.Auto}); 

    var label = new Label {Content = d}; 
    grid.Children.Add(label); 
    Grid.SetColumn(label, 0); 

    var comboBoxItem = new ComboBoxItem {Content = grid, Tag = d}; 
    return comboBoxItem; 
}; 

combo.Items.Add(build(0.5)); 
combo.Items.Add(build(1)); 
combo.Items.Add(build(2)); 
... 

我曾嘗試:

combo.Resources.Add(SystemColors.HighlightBrushKey, Brushes.Green); // this does set the back to green (but is not what I want) 
combo.Resources.Add(SystemColors.HighlightTextBrushKey, Brushes.White); // this does not change the text colour to white it stays as black 

理解任何幫助,謝謝。

回答

2

問題是您正在使用Label控件,它定義了一個固定的Black Foreground,然後它不會繼承ComboBoxItem的顏色,該顏色會根據高亮顯示的狀態進行更改。如果你沒有做任何標籤特定的操作(很少使用),請考慮將其切換爲TextBlock。如果你需要保持標籤,你可以做這樣的事情明確地迫使它繼承:

<ComboBox x:Name="MyComboBox"> 
    <ComboBox.Resources> 
     <Style TargetType="{x:Type Label}"> 
      <Setter Property="Foreground" Value="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ComboBoxItem}}, Path=Foreground}" /> 
     </Style> 
    </ComboBox.Resources> 
</ComboBox> 

,或者如果你在代碼中喜歡,你可以單獨設置它們:

... 
var label = new Label { Content = d }; 
label.SetBinding(ForegroundProperty, new Binding("Foreground") { RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(ComboBoxItem), 1) }); 
grid.Children.Add(label); 
... 
+0

感謝您的回答,我可以更改爲TextBlock,並且工作正常。 – TheBlackKnight 2010-02-11 16:01:22