标签:C#.Net组件开发 - 自定义设计器(ComponentDesigner)
作者:C/S框架网  发布日期:2011/08/11 22:56:22
  标签:C#.Net组件开发 - 自定义设计器(ComponentDesigner)

标签:C#.Net组件开发 -  自定义设计器(ComponentDesigner)



在自定义组件上双击或右键弹出菜单(图一),点击"编辑Itmes"打开设计器窗体(图二)



(图一)





(图二)




实现:

新建一个自定义组件,继承Component,给组件定义设计器,
[Designer(typeof(MyComponentDesigner), typeof(IDesigner))]


C# Code:

[Designer(typeof(MyComponentDesigner), typeof(IDesigner))]
[DefaultProperty("Object")]
public partial class ComponentCS : Component
{
   
   /// <summary>
   /// 嵌套的对象,打开属性编辑器可修改这个对象
   /// </summary>
   private MyObject _Object = new MyObject();
   
   public ComponentCS(IContainer container)
   : base()
   {
      container.Add(this);
   }
   
   /// <summary>
   /// 嵌套的对象,打开属性编辑器可修改这个对象
   /// </summary>
   [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
   [Editor(typeof(MyItemEditor), typeof(UITypeEditor))]
   [LocalizableAttribute(true)]
   [Category("Appearance")]
   [Description("MyObject类型对象")]
   public MyObject Object
   {
      get { return _Object; }
      set { _Object = value; }
   }
   
}

//来源:C/S框架网(www.csframework.com) QQ:1980854898



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



最核心功能:

*** 在设计器修改了对象的属性,必须持久化属性的值到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#.Net组件开发 - 设计时使用自定义属性编辑器持久化对象



C/S框架网|原创精神.创造价值.打造精品


扫一扫加作者微信
C/S框架网作者微信 C/S框架网|原创作品.质量保障.竭诚为您服务

上一篇 下一篇