突出显示在组合框中特定项 [英] Highlighting a particular item in a combo box
问题描述
我有我在哪里填充组合框与模板名称的情况。当中模板之一将是一个默认的模板。我想强调的默认模板的名字时,我填充组合框(让用户知道该项目中一个是默认值)。是否可以这样做呢?如果是的话怎么样?我使用的是Windows窗体在C#2.0。
I have a scenario where I am populating a combo box with the template names. Amongst the templates one would be a default template. I want to highlight the default template name when I populate the combo box (so that the user knows which one among the items is the default). Is it possible to do so? If yes how? I am using a Windows Form in C# 2.0.
推荐答案
这取决于你想如何hightlight项目了一下。如果你想呈现大胆的默认项的文本,就可以实现像这样(这个工作,你需要设置 DrawMode
组合框来 OwnerDrawFixed
,当然挂钩DrawItem事件到事件处理程序):
It depends a bit on how you want to hightlight the item. If you want to render the text of the default item in bold, you can achieve that like this (for this to work you need to set the DrawMode
of the ComboBox to OwnerDrawFixed
, and of course hook up the DrawItem event to the event handler):
我已经填充模板对象组合框像这样定义的:
I have populated the combobox with Template objects, defined like this:
private class Template
{
public string Name { get; set; }
public bool IsDefault { get; set; }
public override string ToString()
{
return this.Name;
}
}
...并DrawItem事件是这样实现的
...and the DrawItem event is implemented like this:
private void ComboBox_DrawItem(object sender, DrawItemEventArgs e)
{
if (e.Index < 0)
{
return;
}
Template template = comboBox1.Items[e.Index] as Template;
if (template != null)
{
Font font = comboBox1.Font;
Brush backgroundColor;
Brush textColor;
if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
{
backgroundColor = SystemBrushes.Highlight;
textColor = SystemBrushes.HighlightText;
}
else
{
backgroundColor = SystemBrushes.Window;
textColor = SystemBrushes.WindowText;
}
if (template.IsDefault)
{
font = new Font(font, FontStyle.Bold);
}
e.Graphics.FillRectangle(backgroundColor, e.Bounds);
e.Graphics.DrawString(template.Name, font, textColor, e.Bounds);
}
}
这应该让你在去正确的方向,我希望。
That should get you going in the right direction, I hope.
这篇关于突出显示在组合框中特定项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!