【问题标题】:how to get parent name of a context menu item?如何获取上下文菜单项的父名称?
【发布时间】:2012-02-09 00:46:45
【问题描述】:

我正在尝试获取上下文菜单项的父名称。

所以我在 menuItem_click 上尝试了类似的操作:

Button clikance = (Button)sender;
string ladyGaga = Convert.ToString(clikance.Content);

但它不起作用(无效的强制转换异常)。感谢您的帮助

【问题讨论】:

    标签: windows-phone-7 contextmenu sender


    【解决方案1】:

    我使用不同的方法来获取上下文菜单的发件人按钮。我在“hold_click”上做了一个事件

    我在公共字符串中取回按钮的内容

    private void GestureListener_DoubleTap(object sender, GestureEventArgs e)
    {
        Button clikance = (Button)sender;
        ButtonEnvoyeur = Convert.ToString(clikance.Content);
    }
    

    【讨论】:

      【解决方案2】:

      如果您在调试器中查看引发异常的位置,您会发现 sender 不是 Button,因此尝试显式转换为 Button显然会抛出一个InvalidCastException

      您可以使用VisualTreeHelper 从实际发件人到Button 元素的树上走:

      VisualTreeHelper.GetParent((sender as DependencyObject));

      更新:在您的实例中,senderContextMenu 中的MenuItem。您可以使用VisualTreeHelperMenuItem 获取父ContextMenu,但不幸的是,ContextMenu 不会公开任何使您能够访问所有者的公共成员; Owner 属性是内部的。您可以获取 Toolkit 的源代码并将 Owner 属性公开为 publi,或者使用完全不同的方法。

      您是否考虑过使用 MVVM 框架(例如 MVVM Light)将命令连接到这些上下文菜单项?您当前的方法非常脆弱,一旦更改视觉树就会中断。如果您使用了命令,则可以通过命令参数传递处理所需的任何其他信息。

      【讨论】:

      • 好吧,我已经尝试关注这个msdn.microsoft.com/en-us/library/bb613579.aspx,因为我不知道visualtreeHelper很好,但VS2010不认识描述的一些方法..
      • 因为该文档专门针对 .NET Framework 4,但 Windows Phone 7 的开发使用 Silverlight(它实际上是 Silverlight 3 的修改)。此页面提供了 Silverlight 支持的 VisualTreeHelper 的文档:msdn.microsoft.com/en-us/library/…。白色的蓝色电话图标表示支持 WP7。
      • 我的问题看起来像他的问题stackoverflow.com/questions/4560244/… 但即使有很好的答案我也不知道该怎么做
      • 我试过 UIElement brut = (UIElement)sender; DependencyObject parent = VisualTreeHelper.GetParent(brut); while (parent as Button == null) { parent = VisualTreeHelper.GetParent(parent); } 但我仍然得到一个异常错误
      • 您需要将调试器设置为中断所有异常并查看您尝试强制转换的 sender 参数的类型(假设这是正在抛出异常)。
      【解决方案3】:

      使用 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;
          (...)         
      }
      

      亚历克斯。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多