Welcome 微信登录

首页 / 网页编程 / ASP.NET / ASP.net控件开发系列之七

ASP.net控件开发系列之七2011-01-27LynComponentEditor

“第二选择”

上篇中,关于Editor说了那么多,完了吗?没有,上篇仅仅介绍了操作属性的UITypeEditor而已。还记得DataGrid的属性窗口的下方的“属性生成器...”吗?

当我们点击“属生生成器...”后,IDE弹出一个窗体,提供我们全方位的操作DataGrid属性的交互界面,这个界面比PropertyGrid提供更方便易用的,更符合DataGrid“国情”。所以,用户有了属性窗格之外的第二个选择。

那么这个“属性生成器...”是什么呢?它也是一个Editor,只是它不是一个UITypeEditor,而是一个ComponentEditor,对,它是一个组件编辑器,它不是用来编辑某个属性的,而是用来操作整个控件的。

下面我们就以实例来看看要实现组件编辑器,要做哪些工作?

控件主体类

[
Designer(typeof(MyDesigner)),
Editor(typeof(MyComponentEditor), typeof(ComponentEditor))
]
public class MyControl :WebControl {
}

在这里我们用到了两个Attribute来描述我们的控件主体类:Designer和Editor,第一个为控件主体类关联一个设计器,这里之所以要用到设计器,因为要方便的调用组件编辑器要借助Designer类。第二个Attribute为控件主体类关联了一个编辑器,大家可以看到它的第二个参数变成了ComponentEditor而不是UITypeEditor。

编辑器窗体类

public class MyComponentEditorForm : System.Windows.Forms.Form {
private MyControl _myControl;
public myControlComponentEditorForm(myControl component) {
InitializeComponent();
_myControl = component;
//用_myControl的属性初始化本窗体上的操作控件(如一些TextBox,还以我以前讲到的PropertyGrid的值)。
}
//以下是用户点击确定完成编辑的逻辑纲要
private void okButton_Click(object sender, System.EventArgs e) {
这里使用PropertyDescriptor来为Component赋值与直接用 _myControl.Property_1 = textBox1.Text 这样的逻辑来赋值有一个好处,就是支持操作的Undo功能#region 这里使用PropertyDescriptor来为Component赋值与直接用 _myControl.Property_1 = textBox1.Text 这样的逻辑来赋值有一个好处,就是支持操作的Undo功能
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(_myControl);
try {
PropertyDescriptor property_1 = props["Property_1"];
if (textProperty != null) {
textProperty.SetValue(_myControl, textBox1.Text);
}
}
catch {
}
DialogResult = DialogResult.OK;
Close();
#endregion
}
}