c# - 如何在 wpf 中动态更改组合框特定项目的颜色

标签 c# wpf combobox

<Grid x:Name="LayoutRoot">
    <ComboBox x:Name="com_ColorItems" Height="41" Margin="198,114,264,0" VerticalAlignment="Top" FontSize="13.333" FontWeight="Bold" Foreground="#FF3F7E24"/>
</Grid>

使用上面的代码,我将组合框中的所有项目都涂成了绿色。

private void Window_Loaded(object sender, RoutedEventArgs e)
{
        for (int i = 0; i < 5; i++)
        {
            com_ColorItems.Items.Add(i);
        }
}

使用上面的代码,我已经将五个项目填充到组合框中。现在我想在后面的代码中动态地将第三项 (3) 的颜色更改为“红色”。我该怎么做?

最佳答案

不是在组合框中添加 i 的实际值,而是添加一个 ComboBoxItem:

private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        for (int i = 0; i < 5; i++)
        {
            ComboBoxItem item = new ComboBoxItem();

            if (i == 2) item.Foreground = Brushes.Blue;
            else item.Foreground = Brushes.Pink;

            item.Content = i.ToString();
            com_ColorItems.Items.Add(item);
        }
    }

如果你以后想修改用这个方法创建的ComboBoxItem,你可以这样做:

var item = com_ColorItems.Items[2] as ComboBoxItem; // Convert from Object
if (item != null)                                   // Conversion succeeded 
{
    item.Foreground = Brushes.Tomato;
}

关于c# - 如何在 wpf 中动态更改组合框特定项目的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11271821/

相关文章:

c# - 超链接样式的按钮

c# - 如何创建带有虚线边框或双线边框的文本框

wpf - 在 WPF 应用程序中显示 PDF

python - 迁移到 pygobject、glade 和 gtk3 时使用入口组合框

c# - 将 WPF 组合框 ItemsSource 绑定(bind)到字符串数组时出错

c# - 使用 P/Invoke 有什么缺点

c# - 使用 Moq 模拟具体类方法的返回值

c# - 在 Windows 10 中单击一次 NotifyIcon 不显示

c# - 如何使用相对路径使用 StreamWriter 创建文件?

winapi - 强制组合框位于上方而不是下方的 "dropdown"