C#WPF - ComboBox突出显示文本颜色问题

时间:2010-02-10 17:31:27

标签: c# wpf combobox

我有一个问题,ComboBox突出显示蓝色背景上的黑色文字,突出显示的文字应为白色。

我有使用ComboBoxItems的ComboBox示例,其中Content是一个字符串。在这些情况下,组合框的行为符合预期 - 当组合框放下时,如果你突出显示一个项目,它会在蓝色黑色背景上显示白色文字。

但是我有一个示例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

感谢任何帮助,谢谢。

1 个答案:

答案 0 :(得分:2)

问题是你正在使用Label控件,它定义了一个固定的Black Foreground,然后不继承ComboBoxItem的颜色,该颜色根据突出显示的状态而变化。如果您没有执行任何特定于标签(使用很少),请考虑将其切换为TextBlock。如果您需要保留Label,您可以执行类似的操作以明确强制继承:

<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);
...
相关问题