2010-11-17 51 views
7

对于当前项目,我需要一个包含颜色名称(字符串)的下拉菜单,并在其旁边有一个小的示例方形(图像)。所以,我能够设计一个自定义组合框来实现这一点。但是,我有一个问题....当我从列表中选择一个项目时,颜色示例不显示,只有颜色的名称。 (参见下面的示例)在自定义组合框中绘制图像

扩展菜单:

alt text

项目之后选择:

alt text

为了绘制颜色旁边的串,首先,我使用:

// Draws the items into the ColorSelector object 
    protected override void OnDrawItem(DrawItemEventArgs e) 
    { 
     e.DrawBackground(); 
     e.DrawFocusRectangle(); 

     DropDownItem item = (DropDownItem)Items[e.Index]; 
     // Draw the colored 16 x 16 square 
     e.Graphics.DrawImage(item.Image, e.Bounds.Left, e.Bounds.Top); 
     // Draw the value (in this case, the color name) 
     e.Graphics.DrawString(item.Value, e.Font, new 
       SolidBrush(e.ForeColor), e.Bounds.Left + item.Image.Width, e.Bounds.Top + 2); 

     base.OnDrawItem(e); 
    } 

DropDownItem包含图像和要绘制的字符串。所以......有人知道我需要重写什么,或者我需要做什么才能让ComboBox绘制图像和字符串,就像当列表展开时,当选择某个项目时一样?

非常感谢; 干杯!

回答

7

设置DropDownStyleDropDownList;默认ComboBox使用TextBox来显示所选项目。这就是所选项目与下拉项目显示不同的原因。

+0

完美!这很好用!非常感谢。我不知道控件只是简单地在顶部使用一个TextBox对象;这似乎是一个有趣的(和不明智的)实现。 – JToland 2010-11-17 19:28:10

0

您还必须以类似于OnDrawItem方法的方式重写OnPaint以使其工作。