使用For Each
循环,我测量FlowLayoutPanel
控件中"X"标签的大小:
For Each _Label As Label In _FlowLayoutPanel.Controls
Dim _TextSize As System.Drawing.Size = TextRenderer.MeasureText(_Label.Text, _Label.Font)
_Label.Size = New Size(_TextSize.Width, _TextSize.Height)
Next
如何获得所有这些Label
宽度中最大的Width
值的变量?
您是否尝试使用变量,并且仅在当前标签的大小大于变量的值时才更改该变量的值?
像这样:
Dim maxWidth as Integer = -1
For Each ...
currentWidth = ...
If currentWidth > maxWidth Then
maxWidth = currentWidth
End If
Next
MsgBox(maxWidth)
编辑:
如果您熟悉 LINQ,或者如果您想了解 LINQ,您甚至可以在一行中获取您想要的信息
。Dim maxWidth As Integer = _FlowLayoutPanel.Controls.OfType(Of Label) _
.Select(Of Integer)(Function(x As Label) TextRenderer.MeasureText(x.Text, x.Font).Width) _
.Max
尽管可能的函数可能因Controls
集合的数据类型而异。
Dim LabelMaxWidth As Integer = 0
For Each _Label As Label In _FlowLayoutPanel.Controls
Dim _TextSize As System.Drawing.Size = TextRenderer.MeasureText(_Label.Text, _Label.Font)
_Label.Size = New Size(_TextSize.Width, _TextSize.Height)
If _Label.Width > LabelMaxWidth Then LabelMaxWidth = _Label.Width
Next
您也可以通过使用一些 LINQ 来获取最大Width
:
MsgBox(FlowLayoutPanel.Controls.
OfType(Of Label).
Max(Function(l) TextRenderer.MeasureText(l.Text, l.Font).Width))