简体   繁体   中英

auto size of label height and width in C#

I have a label of size(47, 15) and my form size is(561, 270). When my label.text is so longer than the window size the last part of the text doesn't appear.How can i dynamically re-size the height and width of the label text with respect to my window.That is when the text is longer than the window then the text will be appear at some lines instead of one line. How can i do that????

使用AutoSize属性。

One basic strategy is to set the MaximumSize.Width property so the label cannot grow horizontally beyond the window edge or overlap another control. It will now automatically wrap long text, adding lines vertically.

You may well also want to set the MaximumSize.Height property so the height cannot get out of control either. In which case you also want to set the AutoEllipsis property to True. So that the user can tell that the text was clipped and a ToolTip is automatically displayed when he hovers the mouse over the label.

In my case I used TextRenderer.MeasureText

在此处输入图像描述

using System.Windows.Forms;

namespace MyApp.Views
{
    public partial class test : Form
    {
        public Form1()
        {
            InitializeComponent();
            //I am getting my dynamic content from a TextBox but you can get from any other source
            string content = myTextBox.Text;


            myDynamicSizeLabel.Text = content;

            //calculating the height using TextRenderer.MeasureText and as reference the TextBox size
            var height = TextRenderer.MeasureText(myTextBox.CreateGraphics(), myTextBox.Text, myTextBox.Font, myTextBox.Size, TextFormatFlags.WordBreak).Height;
            
            //set the new size to my Label
            myDynamicSizeLabel.Height = (height == 0 ? myDynamicSizeLabel.Height: height);
            myDynamicSizeLabel.Width = myTextBox.Width;
            //Autosize must be false
            myDynamicSizeLabel.AutoSize = false;
        }
    }
}

It will produce a result like this在此处输入图像描述

i've been scratching my head to find a solution..

use buttons instead of a label

additional... then if you want set flatstyle to flat ang make the boarder 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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