加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 08:05:27 所属栏目:百科 来源:网络整理
导读: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 voi
<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项(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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读