【发布时间】:2015-07-26 07:59:36
【问题描述】:
我想将按钮添加到 FlowLayoutPanel。按钮可能包含较长的文本,单词之间有空格。按钮是 Autosize=true 和 AutoSizeMode = AutoSizeMode.GrowAndShrink。此外,我将MaximumSize 属性设置为(maxwidth,0)。 maxwidth 是面板的宽度。所以按钮不会太宽。
我看到的是,Button 的宽度受 MaximumSize 属性的限制,但是当发生文本换行时,Button 的高度不会自动调整为换行文本的高度。有没有办法解决这个问题?
我也试过这样手动调整按钮的大小:
using (Graphics cg = this.CreateGraphics()) {
SizeF size = cg.MeasureString(button.Text, button.Font, 200);
button.Width = (int)size.Width+20;
button.Height = (int)size.Height+20;
button.Text = someLongTextWithSpaces;
}
但请注意,我在计算的大小上加了 20。它正在工作,但是有没有合适的方法来确定这个额外的大小?也许 2x 填充 + ?????
几个小时后……
我来到了这个似乎工作得很好的版本。
using (Graphics cg = this.CreateGraphics()) {
var fmt = TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.WordBreak;
var prop = new Size(tableLayoutPanel1.Width - 20, 0);
var size = TextRenderer.MeasureText(button.Text, button.Font, prop, fmt);
int border = button.Height - button.Font.Height;
button.Width = (int)size.Width + border;
button.Height = (int)size.Height + border;
button.Text = someLongTextWithSpaces;
}
似乎初始按钮高度是边框+字体高度。所以我计算了减去button.Height-button.font.Height的边框。
根据 Hans 的说法,我现在使用 TextRenderer.MeasureText。我在没有启用 VisualStyles 的情况下对其进行了测试,它运行良好。有什么相关的吗?
【问题讨论】:
-
而不是
maxwidth(如果您手动添加此号码)尝试此FlowLayoutPanel1.ClientRectangle.Width(或者您调用该面板)。 ....例如,在Form_Resize中输入代码:Button1.MaximumSize = New Size(FlowLayoutPanel1.ClientRectangle.Width, 0)(这是vb 代码,请将他转换为c#)....我认为这是c# 代码:Button1.MaximumSize == new Size(FlowLayoutPanel1.ClientRectangle.Width, 0); -
我还将MaximumSize手动设置为固定值。该值是好的,只有高度调整大小不起作用。您也可以在 FormDesigner 中进行测试。添加带有增长/缩小功能的自动调整大小的按钮和带有空格的较长文本。将最大宽度设置为小于文本。按钮宽度有限,但高度没有增长..
-
你为什么加了+20?
-
@Aseem Gautam:只需客串一个值进行测试。找出真正的价值是个问题。
-
您可以使用虚拟对象通过将文本设置为“X”来找出按钮上一行的高度,然后将其设置为“X\r\nX”。区别在于一行按钮文字的高度。
标签: c# winforms button autosize