易于使用的 WinForms 折叠面板控件






4.88/5 (18投票s)
一个快速且简单的 WinForms 手风琴控件,大约 50 行代码。
介绍
一种将手风琴控件功能轻松添加到任何 WinForms 项目的方法。无需第三方工具,无需头痛。请注意,这里的目的不是构建您可以添加到 VS 工具箱中的内容。它只是演示了一种快速将手风琴功能添加到窗体的一种方式。
使用代码
您可以下载演示项目,或者如果您更喜欢,可以按照以下所示将控件添加到您自己的项目中。
要构建您自己的...
首先,您需要两个 16x16 箭头图像 - 一个向上箭头和一个向下箭头(我的图像有点简陋)。互联网上有大量的免费图像,您可能已经有至少几个了。将图像添加到 My.Resources。您需要编辑代码中的图像文件名。
创建一个新的 VB.Net WinForms 项目并添加以下控件
一个 TableLayoutPanel
来容纳所有其他控件。将其命名为“table_Controls”。停靠到左侧,将 CellBorderStyle
设置为 Inset
。添加七行和一列。在添加下面描述的控件后,将前六行的 SizeType
属性设置为 AutoSize
。将底部行设置为 100%。
在第一、三和五行中添加一个 CheckBox。将它们的 FlatStyle 属性设置为 Flat。将 TextAlign 设置为 MiddleCenter,将 ImageAlign 设置为 MiddleLeft。在第二、四和六行中添加 Panel 控件。将它们的大小设置为 188x150。
将此代码添加到窗体
'set the expanded height for the panels Dim expHeight As Integer = 150 Private Sub Form1_Load _ (ByVal sender As Object, ByVal e As System.EventArgs) _ Handles Me.Load 'collapse all the panels (they're expanded in the designer) Panel1.Height = 0 Panel2.Height = 0 Panel3.Height = 0 'or use your down arrow image CheckBox1.Image = My.Resources.Expander_Collapsed16 CheckBox2.Image = My.Resources.Expander_Collapsed16 CheckBox3.Image = My.Resources.Expander_Collapsed16 'Associate a Panel with each CheckBox CheckBox1.Tag = Panel1 CheckBox2.Tag = Panel2 CheckBox3.Tag = Panel3 End Sub Private Sub ControlClick _ (ByVal sender As System.Object, ByVal e As System.EventArgs) _ Handles CheckBox1.Click, CheckBox2.Click, CheckBox3.Click 'find out which checkbox was clicked Dim chkB As CheckBox = CType(sender, CheckBox) 'get the panel tagged to the checkbox Dim pnl As Panel = CType(chkB.Tag, Panel) 'loop thru the controls in the table and 'check or uncheck, collapse or expand accordingly For Each ctrl As Control In table_Controls.Controls If ctrl.GetType.Equals(chkB.GetType) Then Dim chk As CheckBox = CType(ctrl, CheckBox) Dim p As Panel = CType(chk.Tag, Panel) If Object.ReferenceEquals(chk, chkB) AndAlso chk.Checked Then p.Height = expHeight chk.Image = My.Resources.Expander_Expanded16 Else p.Height = 0 chk.Image = My.Resources.Expander_Collapsed16 chk.Checked = False End If End If Next End Sub
单击任何复选框以展开/折叠其面板。该代码会自动折叠一个展开的面板,当您单击另一个面板的复选框时。
历史
- 首次发布于 2012 年 7 月 6 日。
- 7 月 8 日 - 上传了可供下载的演示项目
- 2015 年 6 月 20 日 - 上传了错误修复版本以解决 Invalid Cast 异常。