Skip to main content
 首页 » 编程设计

c#之更改组合框中某些行的背景颜色

2024年02月06日11think

我有一个绑定(bind)的组合框,根据我在记录中返回的值,我想更改组合框中某些行的背景颜色。这可能吗?如果可能的话怎么办?

再多说一点。我正在查看每一行中的一个字段,并根据它的值更改背景颜色。所以我可以更改所有行、某些行或不更改任何行。

谢谢

请您参考如下方法:

使用 ItemContainerStyle 设置每行的项目背景颜色。您可以绑定(bind)到行的数据上下文中的属性,并使用 IValueConverter 来获取适当的画笔。例如,假设项目具有属性“Y”:

<ComboBox> 
    <ComboBox.Resources> 
        <local:BoolToBrushConverter x:Key="BoolToBrushConverter" /> 
    </ComboBox.Resources> 
    <ComboBox.ItemContainerStyle> 
        <Style TargetType="ComboBoxItem"> 
            <Setter Property="Background"  
                    Value="{Binding Y,Converter={StaticResource BoolToBrushConverter}}" /> 
        </Style> 
    </ComboBox.ItemContainerStyle> 
</ComboBox> 

那么“BoolToBrushConverter”将是这样的:

public class BoolToBrushConverter: IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
        return (value as bool? == true) ? Brushes.Green : Brushes.Red; 
    } 
 
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
        throw new NotImplementedException(); 
    } 
}