获取 DropDownMenu 的 SourceControl

编程入门 行业动态 更新时间:2024-10-28 14:28:32
本文介绍了获取 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).

一种简单的替代方法是使用引用 Control 的 Field,其中当前 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

本文发布于:2023-11-03 09:15:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1554783.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:DropDownMenu   SourceControl

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!