使用字典,集合或类对表单控件进行分组

时间:2018-08-09 14:56:58

标签: vb.net winforms class dictionary collections

我正在尝试对表单控件进行分类/分组,以便能够一次将更改应用于多个控件。例如,我可能要启用/禁用它们。

我应该将表单控件添加到集合,字典中还是应该创建类?

理想情况下,我想创建类别和子类别。我将为类别和子类别定义属性。类别的属性将传递到“子”子类别。 例如,如果CategoryA的字体是“ arial”,则子类别A1,A2等的字体也将是“ arial”。 我只将对象“存储”在子类别中。如果您有想法如何使用这种架构,请提出一些建议。

在这个阶段,我创建了字典。我非常确定我无法使用字典和收藏集创建想要的类别/子类别,但这仍然是朝着正确方向(批量更改)迈出的第一步。

字典所面临的问题是控件的特定属性/方法未在IntelliSense中显示。如何使它们可用?

    Public dct As New Dictionary(Of Object, Integer)

    Dim ctlr As Control
    Dim i As Integer

        i = 1

        For Each ctlr In Controls
            dct.Add(ctlr.Name, i)
            i = i + 1
        Next

        For Each Item In dct
            'Enabled is not available
            Item.Enabled = False
        Next

1 个答案:

答案 0 :(得分:0)

我会转储字典并使用List(Of T)。将实际对象添加到列表中,并且属性应该可用。无论如何,这里是字典代码。在线注释和解释。

Public dct As New Dictionary(Of String, Integer)
        'I changed Object to String because that is what you are
        'adding to the dictionary. I don't see where the .Value
        'is ever used so I suggest changint to List(Of Button) or List(Of Control)
Private Sub OpCode2()

            Dim ctlr As Control
            Dim i As Integer

            i = 1
            'This saves the name of the control to the key of the dictionary
            'This is just a string unrelated to a control as far as the dictionary knows
            For Each ctlr In Controls
                dct.Add(ctlr.Name, i)
                i = i + 1
            Next

            For Each Item As KeyValuePair(Of String, Integer) In dct
                'The .Find method returns a control using the control name
                Dim ctrl As Control = Controls.Find(Item.Key, True).FirstOrDefault()
                'The properties inherited from Control will be available in intellisense
                'If you need a property of a particular type of control 
                'you will need to cast ctrl to the type you need
                ctrl.Enabled = False
            Next
End Sub

以下代码使用List(Of T),并且更短,更易于阅读。

Public lst As New List(Of Control)
Private Sub OpCode2()
        Dim ctlr As Control
        For Each ctlr In Controls
            lst.Add(ctlr)
        Next

        For Each Item In lst
            'The list actually contains a reference to the control
            'so properties of Control are available
            Item.Enabled = False
        Next
End Sub