Welcome

首页 / 软件开发 / .NET编程技术 / .NET组件编程(3) Property Editor

.NET组件编程(3) Property Editor2011-09-26 博客园 mapserver上一章遗留的DefaultValueAttribute问题,还没有找到问题所在,我会继续查找资料,找到后会及时 补上。

今天我们讲Component

Property Editor UI,在vs环境中Property Editor有两种,一种是vs自带的 ,一种是Component编写者根据自己需求而重新编写的。在本章中我们这两种都会进行一个简单的学习, vs自带的主要讲Collection Editor。

先来回顾下我们上章没有讲的几个PropertyAttribute:

EditorAttribute:指定Property Editor使用的编辑器。

DesignerSerializationVisibilityAttribute:指定通过Property Editor得到的结果是否保存在代码 中。

LocalizableAttribute:用户要本地化某个窗体时,任何具有该特性的属性都将自动永久驻留到资源 文件中。

代码实例如下,请注意代码中注释说明。

using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing;
using System.Drawing.Design;
using System.Windows.Forms;
using System.Windows.Forms.Design;

namespace Components
{
// 这个例子用到了vs 2005里的List<>,如果vs 2003的朋友请自己去实做 StudentCollection。
// 只要让Property的类型为继承IList的类型,其Property Editor UI都可以用vs自带的。
public class Demo3 : Component
{
public Demo3()
{
_students = new List<Student>(); // 一定要在构造函数中实例话 _students。
}

private List<Student> _students;
private string _grade;

// vs 自带的Editor。
// 如果没有DesignerSerializationVisibilityAttribute的话,对Students设值,值不 能被保存。
// 大家可以把DesignerSerializationVisibilityAttribute注释掉,对Students设值后 ,关闭vs环境,再重新打开项目,观察Students的值没有被保存下来。
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public List<Student> Students
{
get { return _students; }
set { _students = value; }
}

// 用户自定义Editor。
[Editor(typeof(GradeEditor), typeof(UITypeEditor)), LocalizableAttribute (true)]
public string Grade
{
get { return _grade; }
set { _grade = value; }
}
}

public class Student
{
private int _id;
private string _name;

public int Id
{
get { return _id; }
set { _id = value; }
}

public string Name
{
get { return _name; }
set { _name = value; }
}
}

public class StudentCollection : CollectionBase
{

}

public class GradeEditor : UITypeEditor
{
[System.Security.Permissions.PermissionSet (System.Security.Permissions.SecurityAction.Demand)]
public override System.Drawing.Design.UITypeEditorEditStyle GetEditStyle (System.ComponentModel.ITypeDescriptorContext context)
{
// UITypeEditorEditStyle有三种,Modal是弹出式,DropDown是下拉式,None 是没有。
return UITypeEditorEditStyle.Modal;
}

[System.Security.Permissions.PermissionSet (System.Security.Permissions.SecurityAction.Demand)]
public override object EditValue(System.ComponentModel.ITypeDescriptorContext context, System.IServiceProvider provider, object value)
{
// 得到editor service,可由其创建弹出窗口。
IWindowsFormsEditorService editorService = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));

// context.Instance —— 可以得到当前的Demo3对象。
// ((Demo3)context.Instance).Grade —— 可以得到当前Grade的值。

frmGradeEditor dialog = new frmGradeEditor();
editorService.ShowDialog(dialog);
String grade = dialog.Grade;
dialog.Dispose();

return grade;
}
}
}