为 winforms ComboBox 中的单个项目着色? [英] Colour Individual Items in a winforms ComboBox?
问题描述
我有一个两难选择,我有一个包含许多组合框的表单,其中包含在某些情况下可能无效/过时的信息/选项/项目.
I have a dilemma whereby I have a form which contains a number of comboboxes that contain information/options/items that may be invalid/out-of-date in certain circumstances.
我不能简单地从项目中删除过时的信息,但我确实希望在选项无效时为用户提供视觉线索.
I can't simply remove the out-of-date information from the items, but I do want to give the user a visual-clue when options are invalid.
我想在项目中着色(可能是红色)以表明是否 &当它们无效时.我不一定需要阻止用户选择无效选项,只需让他们在视觉上意识到他们正在这样做.
I was thinking of colouring in the Items (probably red) to indicate if & when they are invalid. I don't necessarily need to prevent a user from selecting an invalid option, just make them visually aware that they are doing so.
这能做到吗?你能 - 动态地 - 改变组合框项目的颜色吗?
Can this be done? Can you - dyamically - change the colo(u)r of combobox items?
谢谢,
推荐答案
你可以试试 ComboBox 的 DrawItem 事件.将您的日期列在清单上,并将它们与 ID 进行比较,然后刷您的项目.
You may try DrawItem event of ComboBox. Keep your dates on a list and compare them with ID's and brush your items.
private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
{
// Draw the background
e.DrawBackground();
// Get the item text
string text = ((ComboBox)sender).Items[e.Index].ToString();
// Determine the forecolor based on whether or not the item is selected
Brush brush;
if (YourListOfDates[e.Index] < DateTime.Now)// compare date with your list.
{
brush = Brushes.Red;
}
else
{
brush = Brushes.Green;
}
// Draw the text
e.Graphics.DrawString(text, ((Control)sender).Font, brush, e.Bounds.X, e.Bounds.Y);
}
触发此事件(感谢@Bolu)
To fire this event (thanks to @Bolu)
你需要改变 ComboBox.DrawMode到 OwnerDrawFixed/OwnerDrawVariable 到触发 comboBox_DrawItem
You need to change ComboBox.DrawMode to OwnerDrawFixed/OwnerDrawVariable to fire the comboBox_DrawItem
这篇关于为 winforms ComboBox 中的单个项目着色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!