C#WPF - 突出显示文本颜色问题的组合框突出显示
突然显示黑色文本的突出显示黑色文本时,突出显示的文本应为白色时,我遇到了突出显示问题。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
理解任何帮助,谢谢。
问题是您正在使用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);
...
感谢您的回答,我可以更改为TextBlock,并且工作正常。 – TheBlackKnight 2010-02-11 16:01:22