问题
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 ContextMenu
s with of these child StackPanel
s.
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 ContextMenu
s 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 MenuItem
s under all 3 ContextMenu
s 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