Combobox外观 [英] Combobox appearance
问题描述
我可以更改Winforms ComboBox的外观,使得 DropDownStyle = DropDownList
的Combobox看起来更像是 DropDownStyle = DropDown
。它们之间的功能差异是前者不允许用户输入的值,问题是它的默认颜色方案看起来变灰,并且与同一对话框上的文本框不匹配。
DropDownList
获得 DropDown
通过将 DrawMode
属性更改为 DrawMode.OwnerDrawFixed
并自己处理项目绘制(幸运的是,这很容易)。示例类,实现此想法: public class ComboBoxEx:ComboBox
{
public ComboBoxEx b $ b {
base.DropDownStyle = ComboBoxStyle.DropDownList;
base.DrawMode = DrawMode.OwnerDrawFixed;
}
protected override void OnDrawItem(DrawItemEventArgs e)
{
e.DrawBackground();
if(e.State == DrawItemState.Focus)
e.DrawFocusRectangle();
var index = e.Index;
if(index< 0 || index> = Items.Count)return;
var item = Items [index];
string text =(item == null)?(null):item.ToString();
using(var brush = new SolidBrush(e.ForeColor))
{
e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
e.Graphics.DrawString(text,e.Font,brush,e.Bounds);
}
}
}
Can I change the appearance of a Winforms ComboBox so that a Combobox with DropDownStyle = DropDownList
looks more like one that is DropDownStyle = DropDown
. The functional difference between them is that the former doesn't allow for user entered values, the problem is that it's default color scheme looks grayed out and doesn't match with textboxes on the same dialog.
you can get DropDown
appearance from DropDownList
style by changing DrawMode
property to DrawMode.OwnerDrawFixed
and handling item painting by yourself (thankfully, that's easy). Sample class, implementing this idea:
public class ComboBoxEx : ComboBox
{
public ComboBoxEx()
{
base.DropDownStyle = ComboBoxStyle.DropDownList;
base.DrawMode = DrawMode.OwnerDrawFixed;
}
protected override void OnDrawItem(DrawItemEventArgs e)
{
e.DrawBackground();
if(e.State == DrawItemState.Focus)
e.DrawFocusRectangle();
var index = e.Index;
if(index < 0 || index >= Items.Count) return;
var item = Items[index];
string text = (item == null)?"(null)":item.ToString();
using(var brush = new SolidBrush(e.ForeColor))
{
e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
e.Graphics.DrawString(text, e.Font, brush, e.Bounds);
}
}
}
这篇关于Combobox外观的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!