[英]auto size of label height and width in C#
我有一个大小为 (47, 15) 的 label,我的表单大小为 (561, 270)。 当我的 label.text 比 window 大小时,文本的最后一部分不会出现。我如何动态调整 label 文本相对于我的 window 的高度和宽度。那是当文本是比 window 长,则文本将出现在某些行而不是一行。 我怎样才能做到这一点????
使用AutoSize属性。
一个基本策略是设置MaximumSize.Width属性,使标签不能水平增长超出窗口边缘或与另一个控件重叠。 它现在将自动换行长文本,垂直添加行。
您可能还想设置MaximumSize.Height属性,以便高度也不会失控。 在这种情况下,您还要将AutoEllipsis属性设置为True。 因此,当用户将鼠标悬停在标签上时,用户可以判断文本已被剪切并自动显示工具提示。
在我的例子中,我使用了 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;
}
}
}
我一直在挠头寻找解决方案..
使用按钮而不是 label
附加...然后如果你想设置 flatstyle 到 flat ang 使寄宿生 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.