Combobox外观

时间:2010-09-24 17:40:01

标签: c# winforms .net-2.0 combobox

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

2 个答案:

答案 0 :(得分:14)

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

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

答案 1 :(得分:2)

你可以尝试更改FlatStyle属性,看看你是否能得到更多你想要的东西。如果您确实希望它看起来像DropDownStyle设置为DropDown那样,您可以将DropDownStyle设置为DropDown并使用KeyPress事件:< / p>

private void comboBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    e.Handled = true;
}

仍然,我可能不这样做,因为ComboBox的外观是用户的视觉提示,表明他们是否应该能够在文本区域中输入。

相关问题