对于像 ComboBox 等控件 , 我们可以通过设置它们的 DrawMode 特性 (Attribute) 来对其进行绘制 .
为了方便起见 , 我们先定义一个类 StringColorObject( 这与 OwnerDraw 本身没有关系 , 只是针对这里要使用到的 ComboBox 而特意书写的一个类 . 类的命名得益于 QuickStart). 这个类本身很简单 :
using System.Drawing;
namespace OwnerDrawSample
{
public class StringColorObject
{
//field to hold the string representing the color
private string colorRepresent;
//field to hold the actually color,the value of the string colorRepresent
private Color color;
//the constructor
//takes 2 parameters, the color representation and the color itself
public StringColorObject( string colorRepresent,Color color)
{
this .colorRepresent = colorRepresent;
this .color = color;
}
//some attributes
public string ColorRepresentation
{
get
{
return this .colorRepresent;
}
//Only getter,no setter
}
public Color Color
{
get
{
return this .color;
}
//only getter,no setter
}
//override the ToString method in System.Object
public override string ToString()
{
return this .colorRepresent;
}
//override the GetHashCode method
public override int GetHashCode()
{
//return the key field’s hash code
return this .color.GetHashCode();
}
//override the Equals method
public override bool Equals( object obj)
{
if (!(obj is StringColorObject))
return false ;
return this .color.Equals(((StringColorObject)obj).color);
}
}
}
建立一个 Windows Application, 并从工具箱中拖拽一个 ComboBox 到 Form 中去 , 并命名为 cmbColors 然后在 Form 的构造函数中添加 :
//
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//
this .FillComboxColor( this .cmbColors);
this .cmbColors.SelectedIndex = 0;
其中 ,FillComboxColor(ComboBox ) 为自定义函数 , 它用来填充参数指定的 ComboBox 对象 . 它的实现为 :
private void FillComboxColor(ComboBox cmb){
cmb.Items.AddRange( new Object[]{
new StringColorObject(" 黑色 (black)",Color.Black),
new StringColorObject(" 蓝色 (blue)",Color.Blue),
new StringColorObject(" 深红 (dark red)",Color.DarkRed),
new StringColorObject(" 绿色 (green)",Color.Green),
//……
});
}
上面只是一些准备工作 ,OwnerDraw 的实际工作现在才刚刚开始 . 将 ComboBox 对象 cmbColors 的 DrawMode 设置为 OwnerDrawFixed( 或是 OwnerDrawVariable, 这里设置为 OwnerDrawFixed 模式 ). 附带说明一下 :DrawMode 可以取 Normal,OwnerDrawFixed 和 OwnerDrawVariable 三者之一 . 其中 ,Normal 模式表示控件由操作系统绘制 , 并且元素的大小都相等 ;OwnerDrawFixed 模式表示控件由手工绘制 , 并且元素的大小都相等 ;OwnerDrawVariable 则是表示控件由手工绘制 , 并且元素的大小可以不相等。
下面开始 OwnerDraw 的核心部分 :
- 撰写控件的 MeasureItem 事件
当要显示 ComboBox 的某一项 (Item) 的时候 [ 即是单击 ComboBox 的下拉按钮时 ], 这个事件会被首先唤起。它用来测量 Item 的长度 , 宽度信息。例如 :
// 注册事件
this .cmbColor.MeasureItem += new MeasureItemEventHandler( this .cmbColor_MeasureItem);
// 实现 cmbColor_MeasureItem--- 测量 ComboBox 的每一个 Item
private void cmbColor_MeasureItem( object sender, System.Windows.Forms.MeasureItemEventArgs e)
{
// 一般来说 , 这里需要设置的是 MeasureItemEventArgs 对象 e 的 ItemHeight 属性和 ItemWidth 属性
ComboBox cmb = (ComboBox)sender;
e.ItemHeight = cmb.ItemHeight;// 当然 , 你可以写 e.ItemHeight = 20;
// 不过对于 OwnerDrawFixed 模式 , 这个函数好像都是多余 .( 对于 ComboBox <SPAN sty