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.