如何调整表单大小以自动适应其内容?

我试图实现以下行为:

在表格上有一个tabcontrol。 在那个tabcontrol上有一个树视图。 为防止出现滚动条,我希望表单在第一次显示时根据树视图的内容更改其大小。

如果树视图中有太多节点要显示在表单的默认大小上,则表单应更改其大小,以便树视图上没有垂直滚动条(最大为屏幕大小允许的最大大小)。

我需要知道的是,是否可以通过控件的属性实现此行为。 我确信这可以通过以编程方式计算和设置元素的大小来实现,但我想知道是否有办法通过AutoSizeMode等设置实现这一点。

[UPDATE]

这是我的应用程序的用户看到的第一个对话框:它是一个选择要使用的数据库的对话框。 这是一个数据库列表,带有tabcontrol,buttens等。如果列表太长,则会出现滚动条,我的同事希望它们消失。

使用AutoSize和AutoSizeMode属性。

http://msdn.microsoft.com/en-us/library/system.windows.forms.form.autosize.aspx

一个例子:

private void Form1_Load(object sender, EventArgs e) { // no smaller than design time size this.MinimumSize = new System.Drawing.Size(this.Width, this.Height); // no larger than screen size this.MaximumSize = new System.Drawing.Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, (int)System.Windows.SystemParameters.PrimaryScreenHeight); this.AutoSize = true; this.AutoSizeMode = AutoSizeMode.GrowAndShrink; // rest of your code here... } 

通过使用各种大小调整属性(Dock,Anchor)或容器控件(Panel,TableLayoutPanel,FlowLayoutPanel等),您只能指定从外部控件到内部控件的大小。 但是.Net框架中没有任何(工作)允许通过子控件的大小来决定容器的大小。 我也错过了几次并尝试了AutoSize属性,但它从未奏效。

所以你所能做的就是试图手动完成这些工作,抱歉。

来自MSDN :

为了最大限度地提高工作效率,Windows窗体设计器AutoSizeForm类的AutoSize属性。 在设计时 ,表单的行为就像AutoSize属性设置为false一样 ,无论其实际设置如何。 在运行时 ,不会进行任何特殊调整,并且按属性设置的指定应用AutoSize属性。

您可以通过计算节点的高度,将其乘以节点数,然后相应地设置表单的MinimumSize属性来计算TreeView所需的高度。

 // assuming the treeview is populated! nodeHeight = treeview1.Nodes[0].Bounds.Height; this.MaximumSize = new Size(someMaximumWidth, someMaximumHeight); int requiredFormHeight = (treeView1.GetNodeCount(true) * nodeHeight); this.MinimumSize = new Size(this.Width, requiredFormHeight); 

NB。 这假设treeview1是表单上唯一的控件。 设置requiredFormHeight变量时,您需要允许树视图周围的其他控件和高度要求,例如您提到的tabcontrol。

(但我会同意@jgauffin并评估在未经用户同意的情况下每次加载时调整表单大小的要求背后的理由 – 可能让用户定位并调整表单大小并记住它而不是??)

这可能很有用。 它将新表单的大小调整为用户控件,然后将用户控件锚定到新表单:

 Form f = new Form(); MyUserControl muc = new MyUserControl(); f.ClientSize = muc.Size; f.Controls.Add(muc); muc.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; f.ShowDialog(); 

这个技术解决了我的问题:

在父母forms:

 frmEmployee frm = new frmEmployee(); frm.MdiParent = this; frm.Dock = DockStyle.Fill; frm.Show(); 

在子表单中(Load事件):

 this.WindowState = FormWindowState.Maximized; 

如果您尝试根据表单填写内容,则以下内容将有所帮助。 当我试图使表单上的内容适合表单resize时,它可以帮助我。

this.contents.Size = new Size(this.ClientRectangle.Width,this.ClientRectangle.Height);

我使用这个代码,它工作得很好

 const int margin = 5; Rectangle rect = new Rectangle( Screen.PrimaryScreen.WorkingArea.X + margin, Screen.PrimaryScreen.WorkingArea.Y + margin, Screen.PrimaryScreen.WorkingArea.Width - 2 * margin, Screen.PrimaryScreen.WorkingArea.Height - 2 * (margin - 7)); this.Bounds = rect;