标签:C#.Net组件开发 - 自定义设计器持久化对象的属性


最核心功能:
*** 在设计器修改了对象的属性,必须持久化属性的值到xxx.Designer.cs文件中 ***
很多朋友在此忘而却步,不知如何处理了,他们反复在问:为什么我修改了对象的属性,再次打开窗体时属性的值不见了?知道这是为什么吗?那里因为你开发的组件没有生成设计时持久化代码!
生成设计时持久化代码:
C# Code:
//取出Object属性的PropertyDescriptor,派生类:ReflectPropertyDescriptor
//PropertyDescriptor:是抽象基类.
PropertyDescriptor pd = TypeDescriptor.GetProperties(c)["Object"];
//当设计器修改了对象的属性,持久化属性的值到Designer.cs文件。
if (pd != null) pd.SetValue(c, c.Object);
//来源:C/S框架网(www.csframework.com) QQ:1980854898
//取出Object属性的PropertyDescriptor,派生类:ReflectPropertyDescriptor
//PropertyDescriptor:是抽象基类.
PropertyDescriptor pd = TypeDescriptor.GetProperties(c)["Object"];
//当设计器修改了对象的属性,持久化属性的值到Designer.cs文件。
if (pd != null) pd.SetValue(c, c.Object);
//来源:C/S框架网(www.csframework.com) QQ:1980854898
xxx.Designer.cs文件内容:
MyComponentDesigner 自定义设计器实现:
C# Code:
/// <summary>
/// 自定义设计器
/// </summary>
public class MyComponentDesigner : ComponentDesigner
{
public MyComponentDesigner()
: base()
{
// 添加"编辑Items"到右键菜单和智能标记中。
DesignerVerb verb = new DesignerVerb("编辑Items", new EventHandler(OnDesignItems));
this.Verbs.Add(verb);
}
private void OnDesignItems(object sender, EventArgs e)
{
this.DoDefaultAction();
}
// 1、可以设计Component的默认事件创建方法签名,并将用户的光标定位到该位置。
// 2、也可以为Component添加双击时要进行的操作。
public override void DoDefaultAction()
{
ComponentCS c = this.Component as ComponentCS;
if (c.Object == null) c.Object = new MyObject();
frmMyObjectEditor editor = new frmMyObjectEditor(c.Object);
//调用属性编辑窗体编辑对象
if (DialogResult.OK == editor.ShowDialog())
{
//取出Object属性的PropertyDescriptor,派生类:ReflectPropertyDescriptor
//PropertyDescriptor:是抽象基类.
PropertyDescriptor pd = TypeDescriptor.GetProperties(c)["Object"];
//当设计器修改了对象的属性,持久化属性的值到Designer.cs文件。
if (pd != null) pd.SetValue(c, c.Object);
}
editor.Dispose();
}
}
//来源:C/S框架网(www.csframework.com) QQ:1980854898
/// <summary>
/// 自定义设计器
/// </summary>
public class MyComponentDesigner : ComponentDesigner
{
public MyComponentDesigner()
: base()
{
// 添加"编辑Items"到右键菜单和智能标记中。
DesignerVerb verb = new DesignerVerb("编辑Items", new EventHandler(OnDesignItems));
this.Verbs.Add(verb);
}
private void OnDesignItems(object sender, EventArgs e)
{
this.DoDefaultAction();
}
// 1、可以设计Component的默认事件创建方法签名,并将用户的光标定位到该位置。
// 2、也可以为Component添加双击时要进行的操作。
public override void DoDefaultAction()
{
ComponentCS c = this.Component as ComponentCS;
if (c.Object == null) c.Object = new MyObject();
frmMyObjectEditor editor = new frmMyObjectEditor(c.Object);
//调用属性编辑窗体编辑对象
if (DialogResult.OK == editor.ShowDialog())
{
//取出Object属性的PropertyDescriptor,派生类:ReflectPropertyDescriptor
//PropertyDescriptor:是抽象基类.
PropertyDescriptor pd = TypeDescriptor.GetProperties(c)["Object"];
//当设计器修改了对象的属性,持久化属性的值到Designer.cs文件。
if (pd != null) pd.SetValue(c, c.Object);
}
editor.Dispose();
}
}
//来源:C/S框架网(www.csframework.com) QQ:1980854898
完整版源码:
C#.Net组件开发 - 设计时使用自定义属性编辑器持久化对象

扫一扫加作者微信


版权声明:本文为开发框架文库发布内容,转载请附上原文出处连接
NewDoc C/S框架网