【问题标题】:Custom CollectionEditor never triggers a property's "set" method自定义 CollectionEditor 永远不会触发属性的“设置”方法
【发布时间】:2011-08-23 15:18:44
【问题描述】:

我正在尝试实现一种将集合保存在自定义设置类中的方法。我已经成功创建了设置类(继承了 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

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

【问题讨论】:

    标签: vb.net visual-studio-2010 propertygrid collectioneditor


    【解决方案1】:

    我想我已经解决了(在this question 的帮助下)。我在自定义编辑器中添加了对 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
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-09
      • 2014-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多