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.
views:
67answers:
2
A:
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.
adrift
2010-09-24 17:58:05
At least in win7 that only changes the border. The interior of the control remains a gray gradient similar to the form background. IIRC in XP the difference between the two drop styles was much less dramatic.
Dan Neely
2010-09-24 18:06:34
+2
A:
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);
}
}
}
max
2010-09-24 18:02:18
Interesting. Is that something you wrote from scratch or pulled from the framework using reflection?
Dan Neely
2010-09-24 18:12:36
It's written from scratch. In fact, this behavior is not really expected. Some time ago I needed to implement a combo box with customized item painting and noticed that changing `DrawMode` property also affects control style, forcing it to `DropDown`.
max
2010-09-24 18:17:49