我有一个 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 的文本内容,因此我可以堆叠多个控件。所以如果里面只有一个“Hello World”,高度应该很小,如果我把 Windows EULA 放在里面它应该很长。
我已经尝试弄乱所有我能得到的“AutoSize”属性,但文本框要么完全消失,要么没有任何效果。
我还尝试在更改时调整文本框的大小:
Size size = TextRenderer.MeasureText(txtContent.Text, txtContent.Font);
txtContent.Height = size.Height;
也没有成功
最佳答案
要使复合控件自动调整大小,请执行以下设置:
- 在用户控件中添加一个
Label
,将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
事件以在内容文本更改时刷新控件的大小:void textBox1_TextChanged(object sender, EventArgs e) { SetBoundsCore(Left, Top, Width, Height, BoundsSpecified.Size); }
结果如下:
关于c# - 按文本内容自动调整面板大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40385206/