【问题标题】:ContextMenuStrip not resizing properlyContextMenuStrip 未正确调整大小
【发布时间】:2015-01-07 10:39:56
【问题描述】:

当我在上下文菜单中更改 ToolStripLabel 的文本时,当我更改菜单项的文本时,上下文菜单不会自动调整其大小。
看起来像这样:

如何正确调整上下文菜单的大小?
我可以更改真实菜单项的文本,但我认为这是一个肮脏的解决方案。


测试表格: (使用鼠标左键,左右两边)

using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1: Form
    {
        private ToolStripLabel menuLabel;

        private void CreateNewContextMenu()
        {
            ContextMenuStrip = new ContextMenuStrip();

            // label
            menuLabel = new ToolStripLabel("hello");
            menuLabel.ForeColor = Color.Blue;
            ContextMenuStrip.Items.Add(menuLabel);

            // items
            ContextMenuStrip.Items.Add("Test");
            ContextMenuStrip.Items.Add("Cut");
            ContextMenuStrip.Items.Add("&Copy");
            ContextMenuStrip.Items.Add("&Paste");
            ContextMenuStrip.Items.Add("&Delete");
        }

        protected override void OnMouseClick(MouseEventArgs e)
        {
            CreateNewContextMenu();
            menuLabel.Text = "hello world hello world hello world";
            Point p = PointToScreen(Point.Empty);

            // left
            if (e.X < ClientSize.Width / 2)
                ContextMenuStrip.Show(p.X + 8, p.Y + 8);
            // right
            else
            {
                ContextMenuStrip.Items[1].Text = menuLabel.Text;
                ContextMenuStrip.Show(p.X + ClientSize.Width - 8, p.Y + 8);
            }

            base.OnMouseClick(e);
        }
    }
}

【问题讨论】:

    标签: c# winforms contextmenu toolstrip


    【解决方案1】:

    是的,当您分配该菜单项的 Text 属性时,ContextMenuStrip 不会重新计算布局。可以说它应该懒惰地做,但这看起来很无聊。您必须提供帮助,它是单行的:

        menuLabel.Text = "hello world hello world hello world";
        ContextMenuStrip.PerformLayout();
    

    【讨论】:

    • 谢谢!这是一个干净的解决方案。实际上,它确实重新计算了普通菜单项 (ToolStripItem) 的布局,而不是 ToolStripLabel
    猜你喜欢
    • 2011-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-23
    • 2021-01-11
    • 1970-01-01
    相关资源
    最近更新 更多