How to use a grid of properties in a form to edit any type

I have an application in which I would like to be able to edit any type (font, color, dot, etc.) at runtime and use any of the .Net default editors. (e.g. font / color selection).

Instead of reinventing the wheel, I decided to use property grid management.

If I pass an object, say, a font, to the grid, it lists all the fields separately, without the ability to open the font collector.

Therefore, I created this general wrapper class:

Private Class Wrapper(Of T)
    Private _Value As T
    Public Property Value() As T
        Get
            Return Me._Value
        End Get
        Set(ByVal value As T)
            Me._Value = value
        End Set
    End Property

    Public Sub New(ByVal Value As T)
        Me._Value = Value
    End Sub
End Class

Instead of passing the font object to the grid, I pass the shell instance. Then the property grid behaves as we would like.

This works, but the problem is that the object can be of any type, and I can’t encode something like -

Dim MyWrapper = New Wrapper(of T)(myObject).

, , , - . :

Dim ID As String = "System.Drawing.Font, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
Dim PropertyValue As String = "Arial, 12px, style=Bold, Strikeout"
Dim T As Type = System.Type.GetType(ID)
Dim tc As TypeConverter = TypeDescriptor.GetConverter(T)
Dim o As Object = tc.ConvertFromString(PropertyValue)

, , , .

, reflection.Emit, " ", , .

?

ETA:

, , Grid , , , .

:

Dim f as Font = Nothing

, , , (none) ... .

, Dim myObject As 'Type' = Nothing, .

, , , , . Pradeep ( ) :

Dim genericType As Type = GetType(Wrapper(Of ))
Dim specificType As Type = genericType.MakeGenericType(T)
Dim ci As ConstructorInfo = specificType.GetConstructor(New Type() {T})
Dim wrappedObject As Object = ci.Invoke(New Object() {Nothing})
Me.PropertyGrid1.SelectedObject = wrappedObject

!

+3
1

, . # VB.net

#

Type generic = typeof(Wrapper<>);
Type specific = generic.MakeGenericType(o.GetType());
ConstructorInfo ci = specific.GetConstructor(new Type[] { o.GetType() });
object o1 = ci.Invoke(new object[] { o });
propertyGrid1.SelectedObject = o1;

VB.NET

Dim generic As Type =  Type.GetType(Wrapper<>) 
Dim specific As Type =  generic.MakeGenericType(o.GetType()) 
Dim ci As ConstructorInfo =  specific.GetConstructor(New Type() {o.GetType() })
Dim o1 As Object =  ci.Invoke(New Object(){  o })
propertyGrid1.SelectedObject = o1
+3

Source: https://habr.com/ru/post/1713205/


All Articles