【问题标题】:Can StatusStrip automatically change its height depending on its items' size?StatusStrip 可以根据其项目的大小自动更改其高度吗?
【发布时间】:2012-07-19 08:25:31
【问题描述】:

我有一个包含许多项目的状态条。其中之一是ToolStripStatusLabelSpring = True。 标签的文字太长,看不到。

是否可以让statusstrip变高并多行显示整个文本?

【问题讨论】:

  • 您可以测量标签字符串(其文本)的大小,如果它大于控件的宽度,则根据需要增加高度。 Check here
  • 我认为在这个解决方案中,问题将是使 ToolStripStatusLabel 多行...可能我们需要自己绘制标签并将文本绘制成两行...
  • ToolStripStatusLabel 不支持在多行中呈现文本。您必须创建自己的派生类。这不容易正确处理,ToolStripItem 难以处理,而且自动调整大小变得非常复杂。

标签: c# winforms autosize statusstrip


【解决方案1】:

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

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

这就是我得到的……

在 StatusStrip 的属性中设置 AutoSize = false,这是为了允许调整 StatusStrip 的大小以容纳多行。我假设 statusStrip 名为 ststusStrip1,其中包含名为 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";

【讨论】:

  • 我只需要在您的代码中更改一件事。由于我希望 ToolStrip 收缩,如果某些新文本小于前者,我删除了对字符串宽度的检查并检查 Tag 属性是否设置为 null(如果是,则返回)。所以现在 ToolStrip 来回改变它的高度!再次感谢您!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-16
  • 2019-07-16
  • 2018-09-25
  • 2020-11-22
  • 2023-04-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多