繁体   English   中英

按文本内容自动调整面板

[英]Autosizing panel by text content

我有一个 WinForms 应用程序,我想在其中添加动态停靠到顶部的 UserControls:

this.Controls.Clear();
this.Controls.Add(myCustomControl(){Title="first", content="first text", Dock=DockStyle.Top});
this.Controls.Add(myCustomControl(){Title="second", content="very long text, where......", Dock=DockStyle.Top});

现在myCostumControl [YELLOW] 是具有以下内容的 userControl:

TopTitle [PINK]: A Label, docked to the top
BottomContent [GREEN]: A Panel, Fills out the rest of the Control below the TopTitle (Dockstyle Fill)
TextContent [BLUE]: A multiline Textbox, docked (fill) within the Panel.

所以它看起来像这样:

在此处输入图片说明

现在我需要实现的是,来自 myCustomControl 的高度是根据“TextContent”-TextBox 的 Text-Content,所以我可以堆叠多个控件。 所以如果里面只有一个“Hello World”,高度应该很小,如果我把Windows EULA放在里面,它应该很长。

我已经尝试过弄乱我可以使用的所有“AutoSize”属性,但是文本框要么完全消失,要么没有效果。

我还尝试在更改时调整文本框的大小:

Size size = TextRenderer.MeasureText(txtContent.Text, txtContent.Font);
txtContent.Height = size.Height; 

也没有成功

要使复合控件自动调整大小,请执行以下设置:

  • 为用户控件添加一个Label并将标签的AutoSize设置为 false 并将其高度设置为合适的高度并将其Dock设置为顶部。
  • TextBox添加到用户控件并将其Dock设置为Fill
  • 覆盖SetBoundsCore并计算控件的首选大小:

     protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) { var flags = TextFormatFlags.WordBreak | TextFormatFlags.NoPrefix; var proposedSize = new Size(width, int.MaxValue); var size = TextRenderer.MeasureText(textBox1.Text, textBox1.Font, proposedSize, flags); height = Math.Max(size.Height, textBox1.Font.Height) + label1.Height + 5; base.SetBoundsCore(x, y, width, height, specified); }
  • 处理TextBox TextChanged事件以在内容文本更改时刷新TextBox大小:

     void textBox1_TextChanged(object sender, EventArgs e) { SetBoundsCore(Left, Top, Width, Height, BoundsSpecified.Size); }

结果如下:

在此处输入图片说明

如果您希望myCustomControl自动调整大小,那么显然,您不能对任何子控件使用填充停靠,因为停靠根据父级大小设置子级的大小,并且您希望父级大小根据子级大小进行调整。

因此,您应该为孩子使用表格布局或流布局。 如果您使用表格,则必须对应该适应的行使用自动调整大小。

然后整个布局控件可以设置为自动调整大小,并且应该停靠在顶部(或者可能锚定)。

如果布局控件不适合可见区域,您可以让父级显示垂直滚动条。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM