【问题标题】:How to put an icon in a MenuItem如何在 MenuItem 中放置图标
【发布时间】:2011-07-08 11:19:06
【问题描述】:

有没有办法在 MenuItem 中的文本旁边放置一个图标?

当用户右键单击用户控件时,我使用以下代码显示弹出菜单:

 ContextMenu menu = new ContextMenu();
 MenuItem item = new MenuItem("test", OnClick);
 menu.MenuItems.Add(item);
 menu.Show(this, this.PointToClient(MousePosition));

我想在弹出菜单中的“test”字符串左侧放置一个图标,以便用户更容易识别它。除了将 OwnerDraw 属性设置为 true(因此需要我自己完全绘制菜单项,就像在此示例中所做的那样:http://www.codeproject.com/KB/menus/cs_menus.aspx)之外,还有其他方法吗?

感谢任何帮助。

【问题讨论】:

标签: c# .net winforms .net-2.0


【解决方案1】:

尝试使用 ContextMenuStrip 并将 ToolStripMenuItems 添加到其中。

如果您必须使用 MenuItem,则必须通过 DrawItem 事件将 OwnerDraw 属性设置为 true。

【讨论】:

  • ContextMenuStrip 确实可以胜任。我不知道它的存在。非常感谢!
【解决方案2】:

这个问题在 6 年前的 .NET 2.0 版本中得到了修复。它获得了 ToolStrip 类。代码非常相似:

        var menu = new ContextMenuStrip();
        var item = new ToolStripMenuItem("test");
        item.Image = Properties.Resources.Example;
        item.Click += OnClick;
        menu.Items.Add(item);
        menu.Show(this, this.PointToClient(MousePosition));

【讨论】:

    【解决方案3】:

    如果你绑定到MenuItem,那么我发现解决方案是这样的:

    var dropDownButton = new ToolBarButton();
    dropDownButton.ImageIndex = 0;
    dropDownButton.Style = ToolBarButtonStyle.DropDownButton;
    
    var mniZero = new MenuItem( "Zero", (o, e) => DoZero() );
    mniZero.OwnerDraw = true;
    mniZero.DrawItem += delegate(object sender, DrawItemEventArgs e) {
        double factor = (double) e.Bounds.Height / zeroIconBmp.Height;
        var rect = new Rectangle( e.Bounds.X, e.Bounds.Y,
                             (int) ( zeroIconBmp.Width * factor ),
                             (int) ( zeroIconBmp.Height * factor ) );
        e.Graphics.DrawImage( zeroIconBmp, rect );
    };
    
    var mniOne = new MenuItem( "One", (o, e) => DoOne() );
    mniOne.OwnerDraw = true;
    mniOne.DrawItem += delegate(object sender, DrawItemEventArgs e) {
        double factor = (double) e.Bounds.Height / oneIconBmp.Height;
        var rect = new Rectangle( e.Bounds.X, e.Bounds.Y,
                         (int) ( oneIconBmp.Width * factor ),
                         (int) ( oneIconBmp.Height * factor ) );
        e.Graphics.DrawImage( oneIconBmp, rect );
    };
    
    dropDownButton.DropDownMenu = new ContextMenu( new MenuItem[]{
        mniZero, mniOne,
    });
    

    希望这会有所帮助。

    【讨论】:

    • 这对我不起作用——主要是我必须实现MeasureItem 事件...还必须绘制文本和选择矩形。
    【解决方案4】:

    使用 ContextMenuStrip 控件,您可以在设计器中执行此操作,方法是单击项目并选择“设置图像...”,或者通过更改 ToolStripMenuItem 的 Image 属性以编程方式执行此操作。

    【讨论】:

    • @Bolu - 看看这个链接 - msdn.microsoft.com/en-us/library/…
    • System.Windows.Forms.MenuItem 至少在 .Net 2.0 中没有这样的属性
    • @BaGi - 哈瓦看看这个链接 - msdn.microsoft.com/en-us/library/…
    • @Bibhu,您的链接是针对通常在 WPF 中使用的System.Windows.Controls.MenuItem .. 赞成票来自哪里?
    • @Bibhu:你提到的链接是指.Net 4.0,而我使用的是 2.0。
    猜你喜欢
    • 2015-11-04
    • 1970-01-01
    • 2022-09-30
    • 1970-01-01
    • 2016-01-07
    • 1970-01-01
    • 2020-02-04
    • 1970-01-01
    相关资源
    最近更新 更多