C# WPF:组合框中的多个前景色

C# WPF:组合框中的多个前景色,c#,wpf,combobox,C#,Wpf,Combobox,在XAML中,我们可以为组合框中的每个项目设置特定属性,例如: <ComboBoxItem Foreground="Blue" Background="AntiqueWhite" Content="First Item"/> <ComboBoxItem Foreground="Yellow" Background="Red" Content="Second Item"/> 尝试将ComboBox的项目强制转换为ComboBoxItem类型,然后将其设置为前台属性,而不是

在XAML中,我们可以为组合框中的每个项目设置特定属性,例如:

<ComboBoxItem Foreground="Blue" Background="AntiqueWhite" Content="First Item"/>
<ComboBoxItem Foreground="Yellow" Background="Red" Content="Second Item"/>

尝试将ComboBox的项目强制转换为
ComboBoxItem
类型,然后将其设置为
前台
属性,而不是整个ComboBox的前台:

((ComboBoxItem)ComboBox1.Items[0]).Foreground = Brushes.Red;
更新:

如果通过以下方式从代码向组合框1添加新项目:

ComboBox1.Items.Add(new ComboBoxItem {Content = "Third Item"});
强制转换可以很好地工作,因为上面的代码类似于您所讨论的XAML对应代码。但如果你是这样做的:

ComboBox1.Items.Add("Third Item");
铸造不起作用。因为该代码将字符串添加到ComboBox项而不是ComboBoxItem对象。在这种情况下,获取ComboBoxItem并不是那么简单,您需要使用
ItemContainerGenerator
获取它,如下所示:

var comboBoxItem = (ComboBoxItem)ComboBox1.ItemContainerGenerator.ContainerFromItem(ComboBox1.Items[0]);
comboBoxItem.Foreground = Brushes.Red;
试试这个:

XAML

<Grid>
    <ComboBox Name="TestComboBox"
              Width="100"
              Height="30"
              Loaded="TestComboBox_Loaded">

        <ComboBoxItem Content="First Item"/>            
        <ComboBoxItem Content="Second Item"/>
    </ComboBox>
</Grid>

我不在电脑附近,你知道有哪些选择吗?也许一个
if
语句可以帮助您。比如:
if(comboBox1.Content==“First Item”){comboBox1.Foreground=brusks.Red}
Nice one!演员阵容非常强大helpful@har07:答案很好,非常感谢:)
<Grid>
    <ComboBox Name="TestComboBox"
              Width="100"
              Height="30"
              Loaded="TestComboBox_Loaded">

        <ComboBoxItem Content="First Item"/>            
        <ComboBoxItem Content="Second Item"/>
    </ComboBox>
</Grid>
private void TestComboBox_Loaded(object sender, RoutedEventArgs e)
{
    var comboBox = sender as ComboBox;

    if (comboBox != null) 
    {
        var firstItem = comboBox.Items[0] as ComboBoxItem;
        var secondItem = comboBox.Items[1] as ComboBoxItem;

        if (firstItem != null && secondItem != null)  
        {
            firstItem.Foreground = Brushes.Red;
            secondItem.Foreground = Brushes.Blue;
        }
    }
}