c# - StatusStrip 能否根据其项目的大小自动更改其高度?

标签 c# winforms autosize statusstrip

我有一个包含许多项目的状态条。其中之一是带有 Spring = TrueToolStripStatusLabel。 标签的文字太长时,会让人看不清。

是否可以使状态条变高并以多行显示整个文本?

最佳答案

这是一个有趣的问题....我尝试了几件事但没有成功...基本上 ToolStripStatusLabel 的功能非常有限。

我最终尝试了一个 hack 来给出你想要的结果,但我不确定我是否会推荐这个,除非这是绝对必要的......

这是我得到的...

在 StatusStrip 的属性中设置 AutoSize = false,这是为了允许调整 StatusStrip 的大小以容纳多行。我假设名为 ststusStrip1 的 statusStrip 包含名为 toolStripStatusLabel1 的标签。

在表单层声明一个TextBox类型的变量:

  TextBox txtDummy = new TextBox();

在表单加载时设置它的一些属性:

  txtDummy.Multiline = true;
  txtDummy.WordWrap = true;
  txtDummy.Font = toolStripStatusLabel1.Font;//Same font as Label

处理toolStripStatusLabel1的绘制事件

 private void toolStripStatusLabel1_Paint(object sender, PaintEventArgs e)
 {        

    String textToPaint = toolStripStatusLabel1.Tag.ToString(); //We take the string to print from Tag
    SizeF stringSize = e.Graphics.MeasureString(textToPaint, toolStripStatusLabel1.Font);
    if (stringSize.Width > toolStripStatusLabel1.Width)//If the size is large we need to find out how many lines it will take
    {
        //We use a textBox to find out the number of lines this text should be broken into
        txtDummy.Width = toolStripStatusLabel1.Width - 10;
        txtDummy.Text = textToPaint;
        int linesRequired = txtDummy.GetLineFromCharIndex(textToPaint.Length - 1) + 1;
        statusStrip1.Height =((int)stringSize.Height * linesRequired) + 5;
        toolStripStatusLabel1.Text = "";
        e.Graphics.DrawString(textToPaint, toolStripStatusLabel1.Font, new SolidBrush( toolStripStatusLabel1.ForeColor), new RectangleF( new PointF(0, 0), new SizeF(toolStripStatusLabel1.Width, toolStripStatusLabel1.Height)));
    }
    else
    {
        toolStripStatusLabel1.Text = textToPaint;
    }
} 

IMP:不要分配标签的文本属性,而是将其放在标签中,我们将从标签中使用它

 toolStripStatusLabel1.Tag = "My very long String";

Screenshot

关于c# - StatusStrip 能否根据其项目的大小自动更改其高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11556785/

相关文章:

c# - 如何使用 OleDbDataAdapter 从 Excel 文件中的任何电子表格中进行选择

c# - 通过匿名类型更新数据库?

C#调用方法参数空引用异常

wpf - 如何将 .NET framework 5.0 添加到 Visual Studio Professional 2019?

ios - UICollectionView 单元格自动调整大小

WPF - 使用用户控件并设置设计时高度和宽度

c# - Selenium 单击 href 中 <li> 中的链接

c# - Windows 窗体、方法和按钮

c# - WinForms DataGridView 抛出 IndexOutOfRangeException