WP7 Finding a ContextMenu's owner

≡放荡痞女 提交于 2019-12-11 13:05:35

问题


I am dynamically populating the contents of a StackPanel in my application by reading an XML file. Each child of the StackPanel is itself another StackPanel which contains different UIElement objects. The reason for the nested StackPanel design is because I want to associate one of 3 different ContextMenus with of these child StackPanels.

So the structure looks like this:

  ---- StackPanel parent
       |
       ---- StackPanel child
       |    |
       |    ---- TextBlock
       |
       ---- StackPanel child
       |    |
       |    ---- TextBox
       |
       ---- StackPanel child
       |    |
       |    ---- Image
       |
       .
       .
       .

For each StackPanel child I'm choosing from amongst 3 ContextMenus and attaching them as follows:

var stackPanels = parentStackPanel.Children.OfType<StackPanel>();

for( int i = 0; i < stackPanels.Count(); ++i ) {
  if( someCondition ) {
    ContextMenuService.SetContextMenu( stackPanels.ElementAt( i ), MyContextMenu1 );

  } else if( someOtherCondition ) {
    ContextMenuService.SetContextMenu( stackPanels.ElementAt( i ), MyContextMenu2 );

  } else {
    ContextMenuService.SetContextMenu( stackPanels.ElementAt( i ), MyContextMenu3 );

  }
}

All MenuItems under all 3 ContextMenus have the same Click handler.

Now, finally, the question: How do I determine which StackPanel child's ContextMenu was invoked and clicked? Inspecting the sender object within the click handler in the debugger shows that a ContextMenu has an internal DependencyObject named Owner which contains a reference to the StackPanel, this is exactly what I want but of course, I can't access it in code that way.

I could solve the problem by adding a MouseLeftButtonDown handler to each child StackPanel, saving the one that was last selected and then retrieving this within the ContextMenu handler but this solution feels a little ugly. Is there a better way to do this?

Thanks in advance for your help!


回答1:


If you cast the sender as a UIElement in the click event handler you should be able to get at whatever you need to identify the actual item which was clicked.

(sender as UIElement).Property

Alternatively cast as a DependencyObject (if possible) and use that to walk the visual Tree:

VisualTreeHelper.GetParent((sender as DependencyObject))


来源:https://stackoverflow.com/questions/4560244/wp7-finding-a-contextmenus-owner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!