我开始创建一个类来轻松地为我的Windows应用程序设置样式。这个概念就是在表单加载时添加对类的引用,然后让类根据样式类中每个控件的属性自动对表单上的每个控件进行样式设置。
我已经创建了一个方法,将表单传递给它,然后循环遍历每个控件,检查它的类型,然后相应地对它进行样式设置。到目前为止没有问题;问题是,如果表单上有一个容器控件(即GroupBox),那么它中的项也需要被循环起来,并检查是否匹配,并相应地设置样式。因此,例如,如果我已经在主循环中检查了一个Button控件,并且它的所有样式代码都在那里,那么如果GroupBox中有一个按钮,它就不会被样式化,除非我把相同的检查和样式代码也放在那个循环中……
可以想象,检查每一种类型的控件+将它的样式代码添加到每个控件中,然后在该循环中的另一个循环中重复完全相同的东西,仅仅为了添加所有相同的检查和样式代码,就会变成大量的代码(更不用说重复的行了)。
我想知道是否有一种更明智的方法来做到这一点,除了将所有样式代码移动到他们自己的Subs中,每个控件,然后在两个循环中复制所有相同的检查,然后只调用每个Sub进行样式设置?(这仍然很混乱,但至少所有的控制风格代码都不是重复的)。
下面是我现在的基本代码;为了清晰起见,我省略了每个控件的所有实际样式代码(在每个控件中都可以看到“控件注释的样式”):
Public Sub MyStyle(ByVal zForm As Form, Optional lstIgnoreControl As List(Of Control) = Nothing)
Try
' Form
With (zForm)
' Style the basic Form properties
End With
Catch ex As Exception
End Try
For Each zCntl As Control In zForm.Controls
' Controls
If zCntl.HasChildren Then
For Each zChildCntl As Control In zCntl.Controls
If zChildCntl.GetType Is GetType(CheckBox) Then
' Style the Checkbox
End If
Next
End If
If IsNothing(lstIgnoreControl) = True OrElse lstIgnoreControl.Contains(zCntl) = False Then
Select Case zCntl.GetType
Case GetType(MenuStrip)
Try
' Style the menustrip
Catch ex As Exception
End Try
Case GetType(StatusStrip)
Try
' Style the Statusstrip
Catch ex As Exception
End Try
Case GetType(Label)
Try
' Style the Label
Catch ex As Exception
End Try
Case GetType(LinkLabel)
Try
' Style the LinkLabel
Catch ex As Exception
End Try
Case GetType(Panel)
Try
' Style the Panel
Catch ex As Exception
End Try
Case GetType(Button)
Try
' Style the Button
Catch ex As Exception
End Try
Case GetType(PictureBox)
Try
' Style the PictureBox
Catch ex As Exception
End Try
Case GetType(DataGridView)
Try
' Style the DataGridView
Catch ex As Exception
End Try
Case GetType(GroupBox)
Try
' Style the GroupBox
Catch ex As Exception
End Try
Case GetType(DateTimePicker)
Try
' Style the DateTimePicker
Catch ex As Exception
End Try
End Select
End If
Next
End SubzCntl.HasChildren循环是我所指的子循环,在这里,冗余将全部进入,我希望避免这种循环。
发布于 2016-08-13 22:06:42
tl;dr
Iterator Function allControls(c As Control) As IEnumerable(Of Control)
Yield c
For Each cc As Control In c.Controls
For Each ccc In allControls(cc)
Yield ccc
Next
Next
End Function样本使用:
For Each gb In allControls(zForm).OfType(Of GroupBox)
' ...
Next或者最好把它们都放在一个LookUp中:
Dim types = allControls(zForm).ToLookup(Function(c) c.GetType)
For Each gb In types(GetType(GroupBox))
' ...
Nexthttps://stackoverflow.com/questions/38937119
复制相似问题