本文介绍了获取 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.

如何在第二张截图的菜单项的点击事件中获取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).

一种简单的替代方法是使用引用 ControlField,其中当前 ContextMenuStrip 已被激活(您可以只有一个活动ContextMenuStrip).
此字段参考,在 ContextMenuStrip 打开时设置 - 通过订阅 Opened() 事件 - 然后可以被任何 ToolStripMenuItem 访问.
ContextMenuStrip 关闭时,Field 引用会被设置回 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.

▶ 当表单关闭时处理 contextMenuOwner 对象.

▶ Dispose of the contextMenuOwner object when the Form closes.

示例:
(toolStripMenuItem 是通用名称,必须设置为实际的控件名称).

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

Control contextMenuOwner = null;

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

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

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

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

09-11 00:25