65.9K
CodeProject 正在变化。 阅读更多。
Home

自定义属性和自定义属性编辑器

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.78/5 (7投票s)

2008年4月17日

CDDL

1分钟阅读

viewsIcon

38293

为用户控件属性定义自己的属性编辑器。

引言

本文档将帮助您为任何用户控件定义自定义数据类型属性,以及自定义属性编辑器。例如,如果您使用字符串数组 (string[]) 作为属性类型,并在属性编辑器中打开该属性,您会看到属性名称旁边显示一个“浏览(…)”按钮。单击“浏览”按钮将打开一个编辑器,允许用户输入多个字符串。 同样,例如,如果用户想要一个分层自定义数据类型列表的属性,那么树形节点编辑器是该属性的最佳编辑器。但是,树形节点编辑器专门用于 TreeNodeCollection 属性。TreeNodeCollection 类是一个密封类,您无法实例化该类,也无法在外部使用它。

文章详情

因此,为了显示分层项目列表,用户可以创建自己的自定义编辑器。我将在这里举一个例子。

自定义数据类型

class DateOfBirth

{

int date;

int month;

int year;

DateOfBirth[] childrenDOB;

}

属性

DateOfBirth[] familyDOB;

属性编辑器

因此,自定义编辑器应该能够显示 familyDOB 的完整层次结构。familyDOB 数组的每个项目作为 treeView 中的根项目,每个项目的子项目作为其各自父节点的 treeview 中的子节点。

实现

public class DateOfBirth
    {
        int date;
        int month;
        int year;
        DateOfBirth[] childrenDOB;
    }

    public class DOBControl : UserControl
    {
        private DateOfBirth[] familyDOB;

        [Editor(typeof(DOBEditor), typeof(System.Drawing.Design.UITypeEditor))]
        public DateOfBirth[] FamilyDOB
        {
            get { return familyDOB; }
            set { familyDOB = value; }
        }

        public object PropertyExplorer(object value)
        {
            DateOfBirth[] _familyDOB=(DateOfBirth[])(value);
            DateOfBirth[] _tempDOB = null;

            //Create the custom property editor instance here
            //custom property editor is exactly similar to default tree node editor
            // 
            //Recursively load nodes and their child nodes in tree view 
            //
            //User can add/remove any nodes in tree view
            //

            //After user closes the property editor here it comes
            //Read all the nodes recursively and create DateOfBirth[] 
            // save in _tempDOB of type DateOfBirth[]

            return _tempDOB;
        }
    }

    public class DOBEditor : System.Drawing.Design.UITypeEditor
    {
        public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
        {
            DOBControl dobControl = (DOBControl)context.Instance;
            return dobControl.PropertyExplorer(value);
        }
    } 

进一步说明

为了使文章简洁明了,我将保持文章非常简短,并且不深入解释。 这适用于一种示例数据类型,并且可以应用于任何数据类型。 我将在下一次更新中尝试上传所有必需的代码和示例。

作者

Vikas Maan, Tektronix, India

© . All rights reserved.