现在的位置: 首页 > 综合 > 正文

为自己的属性编写一个编辑器

2013年10月05日 ⁄ 综合 ⁄ 共 2195字 ⁄ 字号 评论关闭

网上经常有这样的问题:在设计控件时,怎样让自己的属性在属性窗口中显示的时候加一个“…”按钮或者下拉列表框,然后通过自定义的编辑器来编辑该属性的值。我举一个常见的例子,假设你的属性是表示一个路径,你希望在属性窗口中显示时可以有一个“…”按钮,单击之后显示一个目录选取对话框,可以通过它直接选取文件夹。

首先,要编写一个Editor类,继承自System.Drawing.Design.UITypeEditor:

Imports System.Security.Permissions
Imports System.ComponentModel
Imports System.Drawing.Design
Imports System.Windows.Forms

Public Class PathEditor
    Inherits UITypeEditor

    <PermissionSet(SecurityAction.Demand, Name:="FullTrust")> _
    Public Overrides Function EditValue(ByVal context As ITypeDescriptorContext, _
        ByVal provider As IServiceProvider, ByVal value As Object) As Object

        Using chooseDialog As New FolderBrowserDialog()
            With chooseDialog

                .ShowNewFolderButton = False
                .Description = "Choose the folder of " & _
                    context.PropertyDescriptor.DisplayName
                .SelectedPath = CStr(value)
                .RootFolder = Environment.SpecialFolder.MyComputer
                .ShowDialog()
                Return .SelectedPath
            End With
        End Using

    End Function

    <PermissionSet(SecurityAction.Demand, Name:="FullTrust")> _
    Public Overrides Function GetEditStyle( _
        ByVal context As ITypeDescriptorContext) As UITypeEditorEditStyle

        Return UITypeEditorEditStyle.Modal

    End Function

    <PermissionSet(SecurityAction.Demand, Name:="FullTrust")> _
    Public Overrides Function GetPaintValueSupported( _
        ByVal context As ITypeDescriptorContext) As Boolean

        Return False

    End Function

End Class

  在实现这个类时,应当重写UITypeEditor的几个方法。GetEditStyle方法返回一个数,指示编辑器采用外部的编辑器(显示“…”,并弹出窗口)还是使用下拉式列表。本例我们使用外部编辑器。如果不重写这个方法,默认是不会有任何特殊编辑方式的。GetPaintValueSupported方法返回是否支持对属性编辑器重画。我们经常看到颜色属性的编辑器可以直接显示颜色,图标属性的编辑器可以显示图标的缩略图等,都是通过这个功能完成。在这里我们不需要它。最后EditValue属性就是对编辑方式的具体定义。我们需要一个目录选择对话框来编辑目录,就可以在代码中建立它。value参数表示编辑此属性之前属性的值,contex参数则能提供一些有关属性本身的信息。

编写完毕以后,我们就可以给我们的属性绑定这个编辑器。用的是EditorAttribute,例子如下:

<Editor(GetType(PathEditor), GetType(UITypeEditor))> _
Public Property PerlPath() As String
    Get
        Return
_PerlPath
    End Get
    Set
(ByVal value As String)
        _PerlPath = value
    End Set
End Property

这个EditorAttribute要接受两个参数,一个是Editor类的类型,就是刚才我们编写的那个类,一个必须是UITypeEditor本身的类型,用GetType运算符可以获得。现在,你的属性已经可以用自定义的编辑器编辑了。如图:

单击那个编辑按钮以后,弹出编辑器:

还有很多种编辑器,如对集合属性编辑的编辑器,对自定义结构编辑的编辑器等,都可以自由设计,然后通过编写Editor即可用于设计你自己的属性。

抱歉!评论已关闭.