日期:2013-04-04  浏览次数:20367 次

对于像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则是表示控件由手工绘制,并且元素的大小可以不相等。



下面开始OwnerD