代码改变世界

C# 关于开发控件,如何自定义属性归类

2012-06-18 10:33  Andrew.Wangxu  阅读(1858)  评论(0编辑  收藏  举报

首先介绍下属性分类结构:

 

绿色框:是总分类。

红色框:是子分类。

(当然子分类下面还可以包含子分类,跟Node节点一回事。)

灰色框:是子分类下面的属性.

 

Q:如何将自己写的属性归类到指定的总分类

A:使用Category属性,例子如下:

 [Description("The image associated with the control"),Category("Appearance")] 
 public Image MyImage {
    get {
       // Insert code here.
       return image1;
    }
    set {
       // Insert code here.
    }
 }

 

Q:如何自定义一个子分类

A:以创建一个项目作为答案吧,具体步骤如下:

首先看下项目结构图:

  • 1)创建一个C#程序,添加一个UserControl和WinForm。
  • 2)UserControl中代码如下:
  • 2.1)先创建一个类文件MyAttribute,定义复合属性:
namespace WinFormCSharp
{
    [TypeConverter(typeof(ExpandableObjectConverter))]
    public class MyAttribute
    {
        [NotifyParentProperty(true)]
        public int Id { get; set; }
        [NotifyParentProperty(true)]
        public string Name { get; set; }
    }
}

  

【然后在UserControl中引用】

public partial class UserControl1 : UserControl
    {
        private MyAttribute _attr=null;

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public MyAttribute MyAttribute 
        {
            get
            {
                if (_attr == null)
                {
                    _attr = new MyAttribute();
                }
                return _attr;
            }
        }

        public UserControl1()
        {
            InitializeComponent();
        }

    }

最后编译项目,从工具条中拖拽这个控件到WinForm上即可。

参考:http://www.wxzzz.com/?id=104