组合框外观 [英] Combobox appearance

查看:15
本文介绍了组合框外观的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以更改 Winforms ComboBox 的外观,使 DropDownStyle = DropDownList 的组合框看起来更像 DropDownStyle = DropDown 的组合框.它们之间的功能区别在于前者不允许用户输入值,问题在于它的默认配色方案看起来是灰色的,并且与同一对话框中的文本框不匹配.

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.

推荐答案

您可以通过更改 DrawMode 属性从 DropDownList 样式中获得 DropDown 外观到 DrawMode.OwnerDrawFixed 并自己处理项目绘制(谢天谢地,这很容易).示例类,实现这个想法:

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);
        }
    }
}

这篇关于组合框外观的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆