参考链接:http://blogs.msdn.com/b/cumgranosalis/archive/2006/05/18/collapisbleforms.aspx
You know what a collapsible window is – it’s usually used to show advanced features or to show extra information about an error.
有时候我们希望有以下对话框的效果。刚开始时是一个简单的对话框,当我们点击某个按钮后,出现一个另外的信息。而对话框的大小也随着伸缩。
Two examples:
When the error dialog opens, it shows only the basic information so as not to scare the user:
打开一个显示错误信息的对话框,它显示一些简单基本的信息。
When the user clicks on Expand, she sees the extra information:
当用户点击Expand按钮的时候,就可以看到一些详细的信息,这时候对话框也相应变长或变大。
So how do you do this?
There are two ways I employed so far:
1. Quick and dirty: Use constant values when the “Collapse/Expand” button is clicked. Move controls around (namely, the ones containing the buttons at the bottom).
2. Plain dirty: Use hidden controls to act as “markers” – that way, you still have
I usually use method two – it’s as fast as
But now I have a new favorite way of doing this..
By using a FlowLayoutPanel and autoresizing forms, you can get the form to do most of the work
1. Set your form to AutoSize true, and the AutoSizeMode to GrowAndShrink.
Form的AutSize属性设为true, AutoSizeMode设为GrowAndShrink
2.
选择一个FlowLayoutPanel在Form上,选择dock属性为fill
3. Set the panel’s AutoSize to true and it’s AutoSizeMode to GrowAndShrink. Set the FlowDirection to TopDown.
设置FlowLayoutPanel的AutoSize属性为true,AutoSizeMode为GrowAndShrink,FlowDirection属性为TopDown
4. Resize your form to the size you feel comfortable with.
调整Form的大小。
5. Change the MaximumSize property of the form to be the width it currently has with some large number for height (so, if your form has a width of 340, change MaximumSize to be 340,1024). Do the same thing for the panel. If you don’t do this, the form will grow horizontally if labels you have need more space.
改变MaximumSize属性。这不我没有设,不影响效果。
6. Add your controls – in the example above, there’s a label for the error message and a read-only textbox for the details.
加入你想放入的控件。
7. Add your buttons (Okay and “Expand” probably) – you probably want to first add a panel and then add the buttons to that panel.
因为FlowLayoutPanel的FlowDirection属性为TopDown,所以放置在里面的控件都是由上到下排列的,如果希望按自己的方向排列,就先放一个panel,然后再放入自己的控件。如两个按钮就是放在一个panel里,然后将它们放到右边。 8. In
9. In
That’s it. WinForms will do the rest of the heavy lifting for you when the form is shown.
代码如下:
public partial class FrmTest : Form
{
public FrmTest()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.Visible = !textBox1.Visible;
button1.Text = textBox1.Visible ? "Collapse" : " Expand";
}
private void button1_TextChanged(object sender, EventArgs e)
{
button1.Text = textBox1.Visible ? "Collapse" : " Expand";
}
}