我有一个场景,我用模板名称填充一个组合框。在这些模板中,有一个是默认模板。我想在填充组合框时突出显示默认模板名称(以便用户知道项目中的哪一个是默认的)。有可能这样做吗?如果是如何?我在 C# 2.0 中使用 Windows 窗体。
最佳答案
这在一定程度上取决于您希望如何突出显示该项目。如果您想以粗体呈现默认项目的文本,您可以像这样实现(为此,您需要将 ComboBox 的 DrawMode
设置为 OwnerDrawFixed
,当然还有将 DrawItem 事件连接到事件处理程序):
我用模板对象填充了组合框,定义如下:
private class Template
{
public string Name { get; set; }
public bool IsDefault { get; set; }
public override string ToString()
{
return this.Name;
}
}
...DrawItem 事件是这样实现的:
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);
}
}
我希望这能让您朝着正确的方向前进。
关于c# - 突出显示组合框中的特定项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/856397/