Как создать свойство типа Browse для класса со словарем типа - PullRequest
0 голосов
/ 27 сентября 2018

Я создал класс, который наследует кнопку в выигрышных формах. Как я могу создать свойство Browsable с типом dictionary ?

, вот мой код, но я не сделалнайти его в меню свойств vb.net

<Browsable(True)>
Property Set_ddn() As Dictionary(Of TextBox, String)
    Get
        Return ddn
    End Get
    Set(ByVal value As Dictionary(Of TextBox, String))
        ddn = value
    End Set
End Property

как мне сделать его доступным для просмотра?или что я должен использовать вместо словаря?

или другое решение

1 Ответ

0 голосов
/ 05 октября 2018

Я нашел ответ здесь (C #) https://stackoverflow.com/a/42829336/1543991

переписать код для vb.net

Вы должны написать свой собственный дескриптор типа, производный от CustomTypeDescriptor или реализующий ICustomTypeDescriptor,Вот пример:

MyPropertyDescriptor

Укажите пользовательское описание для свойства.Здесь я переопределяю свойство Attributes, чтобы предоставить новый список атрибутов для свойства.Например, я проверяю, имеет ли свойство [Category("Extra")], я также добавил [Browsable(false)] в его коллекцию атрибутов.

Imports System
Imports System.ComponentModel
Imports System.Linq

Public Class MyPropertyDescriptor
Inherits PropertyDescriptor

Private o As PropertyDescriptor

Public Sub New(ByVal originalProperty As PropertyDescriptor)
    MyBase.New(originalProperty)
    o = originalProperty
End Sub

Public Overrides Function CanResetValue(ByVal component As Object) As Boolean
    Return o.CanResetValue(component)
End Function

Public Overrides Function GetValue(ByVal component As Object) As Object
    Return o.GetValue(component)
End Function

Public Overrides Sub ResetValue(ByVal component As Object)
    o.ResetValue(component)
End Sub

Public Overrides Sub SetValue(ByVal component As Object, ByVal value As Object)
    o.SetValue(component, value)
End Sub

Public Overrides Function ShouldSerializeValue(ByVal component As Object) As Boolean
    Return o.ShouldSerializeValue(component)
End Function

Public Overrides ReadOnly Property Attributes As AttributeCollection
    Get
        Dim attributes = MyBase.Attributes.Cast(Of Attribute)().ToList()
        Dim category = attributes.OfType(Of CategoryAttribute)().FirstOrDefault()
        If category IsNot Nothing AndAlso category.Category = "Extra" Then attributes.Add(New BrowsableAttribute(False))
        Return New AttributeCollection(attributes.ToArray())
    End Get
End Property

Public Overrides ReadOnly Property ComponentType As Type
    Get
        Return o.ComponentType
    End Get
End Property

Public Overrides ReadOnly Property IsReadOnly As Boolean
    Get
        Return o.IsReadOnly
    End Get
End Property

Public Overrides ReadOnly Property PropertyType As Type
    Get
        Return o.PropertyType
    End Get
End Property
End Class

MyTypeDescriptor

Используется для предоставлениясписок дескрипторов пользовательских свойств для типа.

Imports System
Imports System.ComponentModel
Imports System.Linq

Public Class MyTypeDescriptor
    Inherits CustomTypeDescriptor

    Private original As ICustomTypeDescriptor

    Public Sub New(ByVal originalDescriptor As ICustomTypeDescriptor)
        MyBase.New(originalDescriptor)
        original = originalDescriptor
    End Sub

    Public Overrides Function GetProperties() As PropertyDescriptorCollection
        Return Me.GetProperties(New Attribute() {})
    End Function

    Public Overrides Function GetProperties(ByVal attributes As Attribute()) As PropertyDescriptorCollection
        Dim properties = MyBase.GetProperties(attributes).Cast(Of PropertyDescriptor)().[Select](Function(p) New MyPropertyDescriptor(p)).ToArray()
        Return New PropertyDescriptorCollection(properties)
    End Function
End Class

MyTypeDescriptionProvider

Используется для подключения MyTypeDescriptor к классу с использованием атрибута TypeDescriptionProvider.

Imports System
Imports System.ComponentModel

Public Class MyTypeDescriptionProvider
    Inherits TypeDescriptionProvider

    Public Sub New()
        MyBase.New(TypeDescriptor.GetProvider(GetType(Object)))
    End Sub

    Public Overrides Function GetTypeDescriptor(ByVal type As Type, ByVal o As Object) As ICustomTypeDescriptor
        Dim baseDescriptor As ICustomTypeDescriptor = MyBase.GetTypeDescriptor(type, o)
        Return New MyTypeDescriptor(baseDescriptor)
    End Function
End Class

MySampleClass

Содержит свойство, украшенное [Category ("Extra")].Так что Property2 не будет виден в сетке свойств.(В визуальной студии или редакторе коллекций или даже в сетке свойств времени выполнения)

<TypeDescriptionProvider(GetType(MyTypeDescriptionProvider))>
Public Class MySampleClass
    Public Property Property1 As Integer
    <Category("Extra")>
    Public Property Property2 As String
End Class

MyComplexComponent

Содержит коллекцию MySampleClass.Таким образом, вы можете увидеть поведение MySampleClass в редакторе коллекций.

Imports System.Collections.ObjectModel
Imports System.ComponentModel

Public Class MyComplexComponent
    Inherits Component

    Public Sub New()
        MySampleClasses = New Collection(Of MySampleClass)()
    End Sub

    <DesignerSerializationVisibility(DesignerSerializationVisibility.Content)>
    Public Property MySampleClasses As Collection(Of MySampleClass)
End Class

enter image description here

...