如何获取上下文菜单项的父名称?
我正在尝试获取上下文菜单项的父名称。
所以我在 menuItem_click 上尝试了类似的操作:
Button clikance = (Button)sender;
string ladyGaga = Convert.ToString(clikance.Content);
但它不起作用(无效的强制转换异常)。感谢您的帮助
I'm trying to get the parent name of a context menu item.
So I tried something like this on menuItem_click :
Button clikance = (Button)sender;
string ladyGaga = Convert.ToString(clikance.Content);
But it didn't work (invalid cast exception). thx for any help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我使用了不同的方法来获取上下文菜单的发件人按钮。我在“hold_click”上做了一个事件
,我在公共字符串中取回了按钮的内容
i have use a different approach for getting the sender button of my context menu. i have made an event on the "hold_click"
where i have get back the content of the button in a public string
如果您在引发异常的调试器中查看,您将看到 sender 不是
Button
,因此尝试显式转换为 < code>Button 显然会抛出InvalidCastException
。您可以使用
VisualTreeHelper
在树中从实际发件人向上走到Button
元素:UPDATE: 在您的实例中 sender< /strong> 是
ContextMenu
中的MenuItem
。您可以使用VisualTreeHelper
从MenuItem
访问父ContextMenu
,但不幸的是,ContextMenu
不会公开使您能够访问所有者的任何公共成员;Owner
属性是内部的。您可以获取 Toolkit 的源代码并将Owner
属性公开为 publi,或者使用完全不同的方法。您是否考虑过使用 MVVM 框架(例如 MVVM Light)将命令连接到这些上下文菜单项?您当前的方法非常脆弱,一旦您更改视觉树就会崩溃。如果您使用命令,则可以通过命令参数传递处理所需的任何附加信息。
If you look in the debugger at the point where the exception is raised, you'll see that sender isn't a
Button
, so trying to do an explicit cast toButton
will obviously throw anInvalidCastException
.You can use the
VisualTreeHelper
to walk up the tree from your actual sender to theButton
element:UPDATE: In your instance sender is the
MenuItem
in theContextMenu
. You can get to the parentContextMenu
from theMenuItem
by using theVisualTreeHelper
, but unfortunately,ContextMenu
does not expose any public members that enable you to access the owner; theOwner
property is internal. You could get the source code for the Toolkit and expose theOwner
property as publi instead, or use a completely different approach.Have you thought of using an MVVM framework (such as MVVM Light) to wire up commands to these context menu items? Your current approach is very fragile and will break as soon as you change the visual tree. If you used commands, you could pass any additional information that you need for processing via the command parameter.
使用 MenuItem 的 Tag 属性来检索您的 Button :
Alex。
Use the Tag property of the MenuItem to retrieve your Button :
Alex.