动态上下文菜单 [英] dynamic context menus

查看:172
本文介绍了动态上下文菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图拿出一个解决方案,以创建一个可以在运行时生成动态上下文菜单。我实现了一个 IGuiCommand 接口实现类似正常Command模式的东西。

I'm trying to come up with a solution to create dynamic context menus that can be generated at run time. I have implemented a IGuiCommand interface that implements something similar to the normal Command pattern.

interface IGuiCommand
{
    Execute();
    Undo();
    bool CanUndo {get;set;}
    Redo();
    string CommandName {get;set;}
    string CommandDescription {get;set;}
}

我们的想法是让这是正确的单击以提交它的命令在给定的上下文菜单中显示的自己的清单控制。

The idea is to allow the control that is Right Clicked to submit it's own list of commands to display in a given context menu.

虽然我可以有每个控件建立一个快捷菜单,我想preFER使用一个单一的快捷菜单,动态地生成菜单,以便在运行时更容易管理。当一个控制状态或应用程序状态的变化,我想在上下文菜单以反映更改。例如,如果我右键单击一个复选框,然后复选框将提交到上下文菜单中启用或禁用命令,显示根据复选框的当前选中的值。

While I could have each control build a context menu, I would prefer to use a single context menu and dynamicly generate the menu to allow easier management during run time. When a control state or application state changes, I would like the context menu to reflect the change. For example if I right click a checkbox, then the checkbox would submit to the context menu an Enable or Disable command to display depending on the checkbox's current Checked value.

我想我可以很容易地实现这一点,如果我有一些办法知道哪些控制是右单击的以调出该特定控制的上下文菜单。

I think I could easily implement this if I had some way to know which control was "Right Clicked" in order to bring up the context menu for that specific control.

这似乎令人惊讶的文本菜单事件不提供的 EventArg ,表明是正确的单击控件(或任何命令,将导致上下文菜单弹出)

It seems surprising the ContextMenu events doesn't supply an EventArg that indicates the control that was right clicked (or whatever command that would cause the context menu to Popup)

推荐答案

您只需要重写ContextMenuStrip_Opening事件。发送者对象是一个的ContextMenuStrip,其中包含一个SourceControl元件。当您应用适当的转换,你将有机会获得你所需要的一切。

You just need to override the ContextMenuStrip_Opening event. The sender object is a ContextMenuStrip, which contains a SourceControl element. When you apply the proper cast, you will have access to everything you need.

private void contextMenuStrip1_Opening(object sender, System.ComponentModel.CancelEventArgs e) {
  var contextMenu = (sender as ContextMenuStrip);
  if (contextMenu != null) {
    var sourceControl = contextMenu.SourceControl;
    contextMenuStrip1.Items.Clear();
    //contextMenuStrip1.Items.Add(...);
  }
}

这篇关于动态上下文菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆