using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.ComponentModel;
using System.Drawing;
namespace CustomControlSample
{
public class FirstControl : Control
{
private String _displayText=”Hello World!”;
private Color _textColor=Color.Red;
public FirstControl()
{
}
// ContentAlignment is an enumeration defined in the System.Drawing // namespace that specifies the alignment of content on a drawing // surface. private ContentAlignment alignmentValue = ContentAlignment.MiddleLeft;
[
Category("Alignment"),
Description("Specifies the alignment of text.")
]
public ContentAlignment TextAlignment
{
get {
return alignmentValue;
}
set {
alignmentValue = value;
// The Invalidate method invokes the OnPaint method described // in step 3. Invalidate();
}
}
[Browsable(
true)]
[DefaultValue(“Hello World”)]
public String DisplayText
{
get {
return _displayText;
}
set {
_displayText =value;
Invalidate();
}
}
[Browsable(
true)]
public Color TextColor
{
get {
return _textColor;
}
set {
_textColor=value;
Invalidate();
}
}
public void ResetTextColor()
{
TextColor=Color.Red;
}
public bool ShouldSerializeTextColor()
{
return TextColor!=Color.Red;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
StringFormat style =
new StringFormat();
style.Alignment = StringAlignment.Near;
switch (alignmentValue)
{
case ContentAlignment.MiddleLeft:
style.Alignment = StringAlignment.Near;
break;
case ContentAlignment.MiddleRight:
style.Alignment = StringAlignment.Far;
break;
case ContentAlignment.MiddleCenter:
style.Alignment = StringAlignment.Center;
break;
}
// Call the DrawString method of the System.Drawing class to write // text. Text and ClientRectangle are properties inherited from // Control. e.Graphics.DrawString(
DisplayText,
Font,
new SolidBrush(TextColor),
ClientRectangle, style);
}
}
}
在上面的代码中,我增加了两个属性,一个是DisplayText,这是一个简单属性,我们只需要在它的声明前添加一个DefaultValue Attribute就可以了。另外一个是TextColor属性,这个复杂类型的属性,所以我们提供了ResetTextColor和ShouldSerializeTextColor来实现默认值。