ContextMenuStrip没有正确调整大小

时间:2015-01-07 10:39:57

标签: c# winforms contextmenu toolstrip

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

enter image description here

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


测试表格 (使用鼠标左键,左侧和右侧)

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);
        }
    }
}

1 个答案:

答案 0 :(得分:4)

是的,当您指定该菜单项的Text属性时,ContextMenuStrip不会重新计算布局。可以说它应该懒得做,但看起来很笨拙。你需要帮助,这是一个单行:

    menuLabel.Text = "hello world hello world hello world";
    ContextMenuStrip.PerformLayout();
相关问题