【发布时间】:2009-04-20 08:08:28
【问题描述】:
对于在 .NET Compact Framework 中省略 Label 和 TextBox 控件的 AutoSize 属性,我简直要疯了。我有一个简单的应用程序,它应该在 TabControl 中列出一堆文本数据(通常在单行到几段文本之间)。其他一切工作顺利,但我尝试动态调整用于显示文本的 Label / TextBox 控件的大小却惨遭失败。
这是我尝试过的方法:
/*
Variables:
s = The text intended for the TextBox
NewTB = TextBox object
width = Intended width
whiteSpaceAdjustment = amount of pixels per line to adjust "wasted" whitespace due to wrapping
*/
String[] linesArray = s.Replace(Environment.NewLine, "\n").Split(new char[] { '\n' });
int lines = 0;
int lineHeight = g.MeasureString(
s.Replace("\n", "").Replace("\r", ""),
LabelFont
).ToSize().Height;
foreach (String str in linesArray) {
if (str.Length == 0) {
lines++;
continue;
}
szz = g.MeasureString(str, LabelFont).ToSize();
lines += szz.Width / (width - whiteSpaceAdjustment);
lines += (szz.Width % width) != 0 ? 1 : 0;
}
NewTB.Height = lines * lineHeight;
NewTB.Width = width;
...但问题是 whiteSpaceAdjustment 所需的范围太大。当它足够大以实际处理最极端的情况(段落主要由非常长的单词组成)时,大多数框最终都会太高一两行。
我可能不得不自己实现自动换行,但在我去那里之前,有没有人为此准备好一个干净的解决方案?
我将永远感激不尽!
【问题讨论】:
标签: c# .net compact-framework