日期:2009-03-05  浏览次数:20456 次

我们先来看看IssueVision中一个用户控件PaneCaption在可视化设计器中的属性窗口.






再看一下在另一个用户控件StaffPane中使用它时的属性窗口:






大家会发现它多出来很多个属性,这些属性是原来继承控件中没有的属性,如:InactiveTextColor,InactiveTextColor等等.它们是如何实现的呢?我们就来看一下这个用户控件的代码PaneCaption.cs吧.

namespace IssueVision
{
// Custom control that draws the caption for each pane. Contains an active
// state and draws the caption different for each state. Caption is drawn
// with a gradient fill and antialias font.
public class PaneCaption : UserControl
{
private class Consts
{
......

可以看到它是由 System.Windows.Forms.UserControl 继承而来,图一显示了它的默认属性.下面我们接着PaneCaption.cs代码,看看是如何将属性或事件显示在可视化设计器中.

[DefaultValueAttribute(typeof(Color), "3, 55, 145")]
[DescriptionAttribute("Low color of the inactive gradient.")]
[CategoryAttribute("Appearance")]
public Color InactiveGradientLowColor
{
get
{
return m_colorInactiveLow;
}

set
{
if (value == Color.Empty)
{
value = Color.FromArgb(3, 55, 145);
}
m_colorInactiveLow = value;
CreateGradientBrushes(); //自定义方法,用于创建线形渐变笔刷
Invalidate(); //Control.Invalidate 方法,使控件的特定区域无效并向控件发送绘制消息
}
}

[CategoryAttribute("Appearance")]
[DescriptionAttribute("High color of the inactive gradient.")]
[DefaultValueAttribute(typeof(Color), "90, 135, 215")]
public Color InactiveGradientHighColor
{
get
{
return m_colorInactiveHigh;
}

set
{
if (value == Color.Empty)
{
value = Color.FromArgb(90, 135, 215);
}
m_colorInactiveHigh = value;
CreateGradientBrushes();
Invalidate();
}
}

[DescriptionAttribute("Text displayed in the caption.")]
[DefaultValueAttribute("")]
[CategoryAttribute("Appearance")]
public string Caption
{
get
{
return m_text;
}

set
{
m_text = value;
Invalidate();
}
}

其结果如下图所示:








我们可以看到Views,Staff list背景都是使用这个自定义的PaneCaption产生渐变效果(由InactiveGradientHighColor和InactiveGradientLowColor属性实现),文字Views和Staff list是由属性Caption实现.




--------------------------------------------------------------------------------

代码分析:

最重要的是 CategoryAttribute 类,它指定属性或事件将显示在可视化设计器中的哪个类别,具体类别如下表:

类别
说明

Action 关于可用操作的属性。
Appearance 影响实体外观的属性。
Behavior 影响实体行为的属性。
Data 关于数据的属性。
Format 影响格式的属性。
Layout 关于布局的属性。
Default 没有类别的属性属于默认类别。













有关更多信息,请参阅.Net Framework 1.1 SDK
我们看到举例的这三个属性CategoryAttribute属性值都为CategoryAttribute("Appearance"),从图二可以看出,这些属性都显示在"外观"下.

DefaultValueAttribute 属性顾名思义,就是此自定义属性的默认值.
DescriptionAttribute 属性则为此自定义属性的描述.


关键部分已经设置完成,剩下的就是如何实现属性的效果了,我以代码说明:

protected override void OnPaint(PaintEventArgs e)
{
DrawCaption(e.Graphics);
base.OnPaint(e);
}

// draw the caption
private void DrawCaption(Graphics g)
{
// background
g.FillRectangle(this.BackBrush, this.DisplayRectangle);

if (m_antiAlias)
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;

// need a rectangle when w