【问题标题】:C# WPF - ComboBox highlighting text colour issueC# WPF - ComboBox 突出显示文本颜色问题
【发布时间】:2011-01-15 09:18:44
【问题描述】:

当突出显示的文本应该是白色时,我遇到了 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

任何帮助表示赞赏,谢谢。

【问题讨论】:

    标签: c# wpf combobox


    【解决方案1】:

    问题在于您使用的是 Label 控件,该控件定义了一个固定的黑色前景,它不会继承 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);
    ...
    

    【讨论】:

    • 感谢您的回答,我可以更改为 TextBlock 并且效果很好。
    猜你喜欢
    • 2012-10-24
    • 2010-09-29
    • 2015-04-25
    • 2013-11-14
    • 2016-03-29
    • 2010-10-18
    • 1970-01-01
    • 1970-01-01
    • 2011-07-02
    相关资源
    最近更新 更多