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.

有帮助吗?

解决方案 2

Using ctacke's solution adopted to the question (constant width of label):

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. Possibly PreferredHeight is not available in CF, if so, use label1.height instead.

其他提示

Use 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);
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top