获取DropDownMenu的SourceControl [英] Get the SourceControl of a DropDownMenu

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

问题描述

我在ContextMenuStrip中有两个菜单项的单击事件。

通过执行以下代码,可以获取所单击的上下文菜单项的SourceControl:

I have two click events of menu items in a ContextMenuStrip.
I can get the SourceControl of the clicked context menu item by doing this code:

Control c = ((sender as ToolStripItem).Owner as ContextMenuStrip).SourceControl;

但是当我在另一个级别的上下文菜单项上使用此代码时,返回null。

But when I use this code on a context menu item that is in another level it, returns null.

我该如何在第二个屏幕快照的菜单项的click事件中获取SourceControl?

How can I get the SourceControl in the click event of the second screenshot's menu item?

推荐答案

ContextMenuStrip SourceControl (激活了上下文菜单的当前控件的引用)可以从 ToolStripMenuItem ,检查 OwnerItem 引用并向上游移动,直到 OwnerItem 引用为 null ,然后检查 Owner 值,该值引用 ContextMenuStrip

(不幸的是, SourceControl 引用是仅在 ContextMenuStrip 控件中可用)。

The ContextMenuStrip SourceControl (the reference of the current Control where the Context Menu is activated) can be retrieved, from a ToolStripMenuItem, inspecting the OwnerItem reference and moving upstream until the OwnerItem reference is null, then inspecting the Owner value, which references the ContextMenuStrip.
(Unfortunately, the SourceControl reference is only available in the ContextMenuStrip control).

一种简单的替代方法是使用引用了 Control 的字段,其中当前 ContextMenuStrip 已被激活(您可以只有一个活动的 ContextMenuStrip )。

此字段引用,在打开 ContextMenuStrip 时设置-订阅 打开ed() 事件-然后可以由任何 ToolStripMenuItem 访问。

字段引用为然后在关闭 ContextMenuStrip 时将其设置回 null

A simple alternative method is using a Field that references the Control where the current ContextMenuStrip has been activated (you can have just one active ContextMenuStrip).
This Field reference, set when the ContextMenuStrip is opened - by subscribing to the Opened() event - can then be accessed by any of the ToolStripMenuItem.
The Field reference is then set back to null when then ContextMenuStrip is closed.

示例

toolStripMenuItem 是通用名称,它

An example:
(toolStripMenuItem is a generic name, it must be set to an actual control name).

Control CurrentContextMenuOwner = null;

private void contextMenuStrip1_Opened(object sender, EventArgs e)
{
    CurrentContextMenuOwner = (sender as ContextMenuStrip).SourceControl;
}

private void toolStripMenuItem_Click(object sender, EventArgs e)
{
    CurrentContextMenuOwner.BackColor = Color.Blue;
    //(...)
}

private void contextMenuStrip1_Closed(object sender, ToolStripDropDownClosedEventArgs e)
{
    CurrentContextMenuOwner = null;
}

这篇关于获取DropDownMenu的SourceControl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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