简体   繁体   English

如何在Windows Mobile 6.5中动态更改标签的高度

[英]How to Change height of label dynamically in windows mobile 6.5

In my app i will get text from server whose length is unknown. 在我的应用程序中,我将从服务器上获取文本,其长度未知。 can some one give idea for how to change the height of label so that the text will not get cutted off if is larger than the length of label. 有人可以提出如何更改标签高度的想法,以使如果大于标签长度,文本不会被截断。

Use Graphics.MeasureString . 使用Graphics.MeasureString Here's a simplified example: 这是一个简化的示例:

public class MyForm : Form
{
    private string m_text;

    public string NewLabelText 
    { 
        get { return m_text; }
        set 
        {
             m_text = value;
             this.Refresh();
        }
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        if (NewLabelText != null)
        {
            var size = e.Graphics.MeasureString(NewLabelText, label1.Font);
            label1.Width = (int)size.Width;
            label1.Height = (int)size.Height;
            label1.Text = NewLabelText;
            NewLabelText = null;
        }

        base.OnPaint(e);
    }
}

Using ctacke's solution adopted to the question (constant width of label): 使用问题采用的ctacke解决方案(标签的恒定宽度):

protected override void OnPaint(PaintEventArgs e)
{
    if (NewLabelText != null)
    {
        //get the width and height of the text
        var size = e.Graphics.MeasureString(NewLabelText, label1.Font);
        if(size.Width>label1.Width){
            //how many lines are needed to display the text
            int iLines = (int)(System.Math.Round((size.Width / label1.Width)+.5));
            //multiply with using the normal height of a one line text
            //label1.Height=iLines*label1.PreferredHeight; //preferredHeight not supported by CF
            label1.Height=(int)(iLines*size.Height*1.1); // add some gutter
        }
        label1.Text = NewLabelText;
        NewLabelText = null;
    }

    base.OnPaint(e);
}

I was unable to test that with CF. 我无法使用CF进行测试。 Possibly PreferredHeight is not available in CF, if so, use label1.height instead. CF中可能不存在PreferredHeight,如果这样,请改用label1.height。

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

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