如何在Flowlayoutpanel内部控件调整大小并使用可用空间?

时间:2017-01-09 14:40:50

标签: vb.net winforms flowlayoutpanel

我有以下屏幕:

enter image description here

我希望发生以下情况:enter image description here

当第二个"隐藏"时,如何让第一个RichTextBox和第三个RichTextBox扩展FlowLayoutPanelRichTextBox设置为RichTextbox2.Visible = false

我们的想法是在FlowLayoutPanel内部显示任何控件,以便在从FlowLayoutPanel内部未使用的数据库加载数据时填充空间,如图2所示。因此,如果还有另一个RichTextBox,则所有3将占用FlowLayoutPanel内的所有可用空间。

我已经尝试了以下建议here,但我无法正确扩展未使用的空间。

2 个答案:

答案 0 :(得分:1)

应该是相当简单的数学......(这里没有任何效率)

'assuming you may have a variable number of richtextboxes you need to get a count of the ones that are visible
'also assuming the richtextboxes are already children of the flowlayoutpanel
'call this sub after you have put the unsized richtextboxes into the FlowlayoutPanel (assuming you are doing that dynamically)    
Private Sub SizeTextBoxes()
    Dim Items As Integer = 0
    'create an array for the richtextboxes you will be sizing
    Dim MyTextBoxes() As RichTextBox = Nothing
    For Each Control As Object In FlowLayoutPanel1.Controls
        If TryCast(Control, RichTextBox).Visible Then
            'create a reference to each visible textbox for sizing later
            ReDim Preserve MyTextBoxes(Items)
            MyTextBoxes(Items) = DirectCast(Control, RichTextBox)
            Items += 1
        End If
    Next

    'if the flowlayoutpanel doesn't have any richtextboxes in it then MyTextBoxes will be nothing
    If Not IsNothing(MyTextBoxes) Then
        'get the height for the text boxes based on how many there are and the height of the flowlayoutpanel
        Dim BoxHeight As Integer = FlowLayoutPanel1.Height \ Items
        For Each TextBox As RichTextBox In MyTextBoxes
            TextBox.Height = BoxHeight
        Next
    End If
End Sub

如果富文本框的数量确实可变 - 您可能想要设置一个限制,这样就不会出现600个1像素高的文本框......

答案 1 :(得分:1)

您可能想要使用TableLayoutPanel:

Private WithEvents tlp As New TableLayoutPanel

Public Sub New()
  InitializeComponent()

  tlp.Location = New Point(150, 16)
  tlp.Size = New Size(Me.ClientSize.Width - 166, Me.ClientSize.Height - 32)
  tlp.Anchor = AnchorStyles.Left Or AnchorStyles.Top Or 
               AnchorStyles.Right Or AnchorStyles.Bottom
  tlp.ColumnCount = 1
  tlp.RowCount = 3
  tlp.ColumnStyles.Add(New ColumnStyle(SizeType.Percent, 100))
  tlp.RowStyles.Add(New RowStyle(SizeType.Percent, 50))
  tlp.RowStyles.Add(New RowStyle(SizeType.Absolute, 32))
  tlp.RowStyles.Add(New RowStyle(SizeType.Percent, 50))

  tlp.Controls.Add(New RichTextBox With {.Dock = DockStyle.Fill}, 0, 0)
  tlp.Controls.Add(New RichTextBox With {.Dock = DockStyle.Fill}, 0, 1)
  tlp.Controls.Add(New RichTextBox With {.Dock = DockStyle.Fill}, 0, 2)

  Me.Controls.Add(tlp)
End Sub

然后隐藏中间一行,切换高度:

If tlp.RowStyles(1).Height = 0 Then
  tlp.GetControlFromPosition(0, 1).Enabled = True
  tlp.RowStyles(1).Height = 32
Else
  tlp.GetControlFromPosition(0, 1).Enabled = False
  tlp.RowStyles(1).Height = 0
End If