Combobox appearance

2019-02-14 05:46发布

问题:

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.

回答1:

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


回答2:

You could try to change the FlatStyle property and see if you get something more to your liking. If you really want it to look like it does with DropDownStyle set to DropDown, you could set the DropDownStyle to DropDown and eat the KeyPress event:

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

Still, I would probably not do this as the appearance of the ComboBox is a visual cue to the user indicating whether they should be able to type in the text area or not.