在.net里要为Control或者Component定制Designer,只要从IDesigner继承下来即可,但是在.net里ms已经帮我们做了两个从IDesigner继承下来的基类,ComponentDesigner和ControlDesigner,ComponentDesigner是为Component而设计的,ControlDesigner是为Control而设计的,所以我们可以直接从ComponentDesigner继承。
Designer可以提供右键快捷菜单上的菜单命令,我们可以通过实现ComponentDesigner 谓词(Verbs) 属性来定义 get 访问器,该访问器返回的 DesignerVerbCollection 中包含用于生成菜单命令的 DesignerVerb 对象。
同时我们对组件被双击时定制默认操作,在Component Designer实现 DoDefaultAction 方法即可。
示例代码如下:
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Windows.Forms;
using System.Windows.Forms.Design;
namespace ClassLibrary1
{
[DefaultEvent("CustomerLogin")]
[Designer(typeof(Class1Designer), typeof(IDesigner)), Editor(typeof(Class1Editor), typeof(ComponentEditor))]
public class Customer : Component
{
private string _parentComponentName;
private int _age;
private string _address;
public delegate void CustomerLoginEventHandler(object sender, CustomerLoginEventArgs e);
public delegate void CustomerLogoutEventHandler(object sender, CustomerLogoutEventArgs e);
public string ParentComponentName
{
get { return _parentComponentName; }
set { _parentComponentName = value; }
}
public int Age
{
get { return _age; }
set { _age = value; }
}
public string Address
{
get { return _address; }
set { _address = value; }
}
public sealed class CustomerLoginEventArgs : EventArgs { }
public sealed class CustomerLogoutEventArgs : EventArgs { }
public event CustomerLoginEventHandler CustomerLogin
{
add { }
remove { }
}