.NET Compact Framework中的标签/文本框自动调整大小

4

我对.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 所需的范围太大了。当它足够大以实际处理最极端的情况(由大多数长单词构成的段落)时,大多数框会变高一两行。

我可能需要自己实现换行,但在这之前,是否有任何人已经有了一个漂亮干净的解决方案呢?

如果有人能够提供帮助,我会永远感激不尽!

2个回答

4

没关系,我自己也遇到了同样的问题。 - stevehipwell

1
这是我为WinCE开发的自动调整标签宽度的内容。
/// <summary>
/// This class provides dynamic size labels, i.e. as the text grows lable width will grow with it. 
/// </summary>
public partial class AutoSizeLabel : UserControl
{
    private string _strText;
    private const int padding = 10;

    public AutoSizeLabel()
    {
        InitializeComponent();
    }

    public override string Text
    {
        get
        {
            return _strText;
        }
        set
        {
            _strText = value;
            Refresh();
        }
    }

    protected override void OnPaint(PaintEventArgs pe)
    {
        SizeF size = pe.Graphics.MeasureString(this.Text, this.Font);
        this.Size = new Size((int)size.Width + padding, this.Height);

        if (this.Text.Length > 0)
        {
            pe.Graphics.DrawString(this.Text,
                this.Font,
                new SolidBrush(this.ForeColor),
                (this.ClientSize.Width - size.Width) / 2,
                (this.ClientSize.Height - size.Height) / 2);
        }
        // Calling the base class OnPaint
        base.OnPaint(pe);
    }
}

这对于宽度非常有效,谢谢分享。有关自动调整高度的任何提示吗?如果不显式设置高度,则标签的高度为150而不是20。 - Zacho
我发现从 this.Controls[i].Width 访问宽度时是正确的,供你参考。 - Zacho
@Zacho:你想要一个宽度固定、高度动态的标签吗? - Muhammad Usman Aleem
不,我希望它完全动态化。但是当我按原样使用此代码时,默认高度为150。奇怪... - Zacho
@Zacho:我不是WinCE编程方面的专家(很抱歉),但我认为你应该将一个字段固定为宽度或高度,以便另一个字段可以是动态的。在给定的代码中,高度是固定的,而调整大小是在宽度上完成的。 - Muhammad Usman Aleem

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接