簡體   English   中英

如何在Windows Mobile 6.5中動態更改標簽的高度

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

在我的應用程序中,我將從服務器上獲取文本,其長度未知。 有人可以提出如何更改標簽高度的想法,以使如果大於標簽長度,文本不會被截斷。

使用Graphics.MeasureString 這是一個簡化的示例:

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);
    }
}

使用問題采用的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);
}

我無法使用CF進行測試。 CF中可能不存在PreferredHeight,如果這樣,請改用label1.height。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM