2009-12-10 10 views
22

Tengo un ContextMenu así:Obtener propietario del menú de contexto en el código

<StackPanel Orientation="Horizontal"> 
    <StackPanel.ContextMenu> 
     <ContextMenu> 
      <MenuItem Header="Delete" Click="OnDeleteClicked" /> 
     </ContextMenu> 
    </StackPanel.ContextMenu> 
</StackPanel> 

Y necesito para obtener la instancia de la StackPanel al cual pertenece ese ContextMenu. Ya he intentado esto:

private void OnDeleteClicked(object sender, System.Windows.RoutedEventArgs e) 
{ 
    FrameworkElement parent = e.OriginalSource as FrameworkElement; 

    while (!(parent is StackPanel)) 
    {    
     parent = (FrameworkElement)LogicalTreeHelper.GetParent(parent); 
    } 
} 

Pero después de conseguir el padre ContextMenu emergente, se hace nula, lo mismo con la VisualTreeHelper, se pone a null antes de conseguir el StackPanel. ¿Alguna idea de como hacerlo?

Gracias!

Respuesta

1

el menú contextual tiene su propio árbol visual, prueba esta llamando a esto desde el controlador de eventos de este modo: -

StackPanel stackPanel = GetStackPanelItemFromContextMenu((FrameworkElement)sender, yourStackPanel); 

    private StackPanel GetStackPanelItemFromContextMenu(FrameworkElement sender, StackPanel stackPanel) { 
    Point menuClickPoint = ((sender as FrameworkElement).Parent as ContextMenu).TranslatePoint(new Point(0, 0), stackPanel); 

    // get the first potential object that was hit 
    DependencyObject obj = stackPanel.InputHitTest(menuClickPoint) as DependencyObject; 

    // cycle up the tree until you hit the StackPanel 
    while (obj != null && !(obj is StackPanel)) { 
     obj = VisualTreeHelper.GetParent(obj); 
    } 

    return obj as StackPanel; 
    } 
48

esto le dará exactamente lo que desea

private void OnDeleteClicked(object sender, System.Windows.RoutedEventArgs e) 
{ 
    MenuItem mnu = sender as MenuItem; 
    StackPanel sp = null; 
    if(mnu!=null) 
    { 
     sp = ((ContextMenu)mnu.Parent).PlacementTarget as StackPanel; 
    } 
} 

Esperanza esta ayuda !!

Cuestiones relacionadas