【问题标题】:StatusStrip label not visible when text too long当文本太长时,StatusStrip 标签不可见
【发布时间】:2016-11-04 10:48:24
【问题描述】:

我有一个 StatusStrip 停靠在 C# 表单的底部,它包含一个标签,其中的文本显示正常,除非文本长度较长,否则它根本不会显示,我必须扩大形式,然后突然出现。是否可以用下面的形式展示出来:

    This is a very long tex...

这样用户就知道应用正在显示一些东西,然后他可以自己扩大它,因为当它根本不可见时,它不会向用户指示任何东西。

【问题讨论】:

  • 只测量文本宽度并在状态标签宽度处修剪它,然后 SubString() + "...";
  • 你用的是什么VS?我正在使用 VS2015 Update 3、.NET 4.0、Win10,没关系。如果表单宽度小于文本宽度,文本将被截断。 “......它根本不显示”在我的表单上没有发生。
  • @JeremyThompson 这是可行的,但是当用户扩展表单时,我必须再次刷新它,否则它会显示不完整的文本。
  • @x... 我正在使用 VS 2010 和 .Net framework 3.5

标签: c# .net winforms statusbar toolstrip


【解决方案1】:

您可以基于ToolStripProfessionalRenderer创建自定义渲染器并覆盖OnRenderItemText方法并使用省略号绘制文本:

public class CustomRenderer : ToolStripProfessionalRenderer
{
    protected override void OnRenderItemText(ToolStripItemTextRenderEventArgs e)
    {
        if (e.Item is ToolStripStatusLabel)
            TextRenderer.DrawText(e.Graphics, e.Text, e.TextFont,
                e.TextRectangle, e.TextColor, Color.Transparent,
                e.TextFormat | TextFormatFlags.EndEllipsis);
        else
            base.OnRenderItemText(e);
    }
}

然后将 RendererStatusStrip 设置为自定义渲染器就足够了:

this.statusStrip1.Renderer = new CustomRenderer();

在下面的示例中,您可以看到ToolStripStatusLabel 的行为,它的Spring 属性设置为true,其StatusStrip 使用CustomRenderer

【讨论】:

  • 我正在使用 VS2015.3、.NET 4.0 和 Win10。这是 statusStrip 中标签的默认行为。我不需要扩展它。
  • @x... 该示例是使用 Windows 8.1 上的 VS 2013.4.NET 4.5 创建的。看来我们需要修复一下。
  • 感谢 @RezaAghaei 我在 VS 2010 和 .Net 3.5 windows 8.1 上
  • 感谢@RezaAghaei 的出色解决方案!请注意,您的回答还应包括仅当您设置了 this.statusStrip1.LayoutStyle = System.Windows.Forms.ToolStripLayoutStyle.Table; 的 LayoutStyle HorizontalStackWithOverflow 时才有效。
【解决方案2】:

如果你设置了

ToolStripStatusLabel.Spring = True;

那么您将不会得到“...”,但即使可用空间不足也会显示文本。

【讨论】:

    【解决方案3】:

    在 Visual Studio 2017 上,接受的答案对我不起作用。所以这是另一个简单的解决方案。 将 StatusStrip 的 LayoutStyle 属性设置为 Flow。即:

     statusStrip1.LayoutStyle= LayoutStyle.Flow;
    

    并设置

    `statusStrip1.AutoSize= false;`
    

    【讨论】:

    • 可能您在应用解决方案时犯了一个错误。确保您已添加状态旅行标签。还要确保您已将标签的 spring 属性设置为 true 并且您正在使用我在答案中发布的渲染器。
    猜你喜欢
    • 2017-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多