1

我正在尝试实现一种将集合保存在自定义设置类中的方法。我已经成功创建了设置类(继承了 ApplicationSettingsBase),并且可以使用 PropertyGrid 上的内置编辑器保存属性,但是我对集合的属性网格的自定义实现不会保留我添加的任何值。这是我的代码:

Imports System.Configuration
Imports System.ComponentModel
Imports System.Drawing.Design
Imports System.ComponentModel.Design

Public Class CustomSettings
    Inherits ApplicationSettingsBase

    <UserScopedSetting()> _
    <DefaultSettingValue("White")> _
    Public Property BackgroundColor() As Color
        Get
            BackgroundColor = Me("BackgroundColor")
        End Get
        Set(ByVal value As Color)
            Me("BackgroundColor") = value
        End Set
    End Property

    <UserScopedSetting()> _
    <DesignerSerializationVisibility(DesignerSerializationVisibility.Content)> _
    <Editor(GetType(CustomStringCollectionEditor), GetType(UITypeEditor))> _
    Public Property EmailAddresses() As Collection
        Get
            EmailAddresses = Me("EmailAddresses")
        End Get
        Set(ByVal value As Collection)
            Me("EmailAddresses") = value
        End Set
    End Property
End Class

Public Class CustomStringCollectionEditor
    Inherits CollectionEditor

    Public Sub New()
        MyBase.New(GetType(Collection))
    End Sub

    Protected Overrides Function CreateInstance(ByVal itemType As System.Type) As Object
        Return String.Empty
    End Function

    Protected Overrides Function CreateCollectionItemType() As System.Type
        Return GetType(String)
    End Function
End Class

我为 BackgroundColor 属性和 EmailAddresses 属性的 Set 方法设置了一个断点。BackgroundColor 属性按其应有的方式工作 - 它在 Set 语句上中断并正确存储该属性。但是当我关闭自定义 CollectionEditor 对话框时,永远不会调用 EmailAddresses“Set”方法。编辑完成后,如何让我的自定义编辑器实际保存属性?

4

1 回答 1

1

我想我修好了(在这个问题的帮助下)。我在自定义编辑器中添加了对 EditValue 函数的覆盖。这是代码:

    Public Overrides Function EditValue(ByVal context As System.ComponentModel.ITypeDescriptorContext, ByVal provider As System.IServiceProvider, ByVal value As Object) As Object
        Dim result As Object = MyBase.EditValue(context, provider, value)
        DirectCast(context.Instance, CustomSettings).EmailAddresses = DirectCast(result, List(Of String))
        Return result
    End Function

我也从一个集合转移到一个列表——我在某个更安全的地方阅读。我还在我的 CustomSettings 类中添加了一个构造函数,它将 EmailAddresses 属性设置为一个新的 List(Of String),如果它一开始就没有设置的话。我发现它第一次运行时,我可以编辑列表并添加项目,但它们不会被持久化:

Public Sub New()
    If Me("EmailAddresses") Is Nothing Then
        Me("EmailAddresses") = New List(Of String)
    End If
End Sub

现在一切正常。但如果这不是最好的方法或有更简单的方法,请加入。

于 2011-05-12T13:18:27.487 回答