我正在尝试获取上下文菜单项的父名称。
所以我在 menuItem_click 上尝试了这样的事情:
Button clikance = (Button)sender;
string ladyGaga = Convert.ToString(clikance.Content);
但它不起作用(无效的演员表异常)。谢谢任何帮助
我正在尝试获取上下文菜单项的父名称。
所以我在 menuItem_click 上尝试了这样的事情:
Button clikance = (Button)sender;
string ladyGaga = Convert.ToString(clikance.Content);
但它不起作用(无效的演员表异常)。谢谢任何帮助
我使用不同的方法来获取上下文菜单的发件人按钮。我在“hold_click”上做了一个活动
我在公共字符串中取回按钮的内容
private void GestureListener_DoubleTap(object sender, GestureEventArgs e)
{
Button clikance = (Button)sender;
ButtonEnvoyeur = Convert.ToString(clikance.Content);
}
如果您在引发异常的位置查看调试器,您会看到sender不是 a Button
,因此尝试进行显式强制转换Button
显然会抛出一个InvalidCastException
.
您可以使用VisualTreeHelper
来从您的实际发件人到Button
元素的树上走:
VisualTreeHelper.GetParent((sender as DependencyObject));
更新:在您的实例中,发件人是. 您可以使用来从 中访问父级,但不幸的是,它不会公开任何使您能够访问所有者的公共成员;该属性是内部的。您可以获取 Toolkit 的源代码并将属性公开为 publi,或者使用完全不同的方法。MenuItem
ContextMenu
ContextMenu
MenuItem
VisualTreeHelper
ContextMenu
Owner
Owner
您是否考虑过使用 MVVM 框架(例如MVVM Light)将命令连接到这些上下文菜单项?您当前的方法非常脆弱,一旦您更改视觉树就会中断。如果您使用了命令,则可以通过命令参数传递处理所需的任何附加信息。
使用 MenuItem 的 Tag 属性来检索您的 Button :
// Object creation
Button myButtonWithContextMenu = new Button();
ContextMenu contextMenu = new ContextMenu();
MenuItem aMenuItem = new MenuItem
{
Header = "some action",
Tag = myButtonWithContextMenu, // tag contains the button
};
// Events handler
aMenuItem.Click += new RoutedEventHandler(itemClick);
private void itemClick(object sender, RoutedEventArgs e)
{
// Sender is the MenuItem
MenuItem menuItem = sender as MenuItem;
// Retrieve button from tag
Button myButtonWithContextMenu = menuItem.Tag as Button;
(...)
}
亚历克斯。