2013-07-11 3 views
1

У меня есть следующее контекстное меню, объявленное в моих ресурсах приложения, и на него ссылаются несколько древовидных представлений в моем приложении. Я пытаюсь отправить свойство SelectedItem TreeView в качестве параметра команды.Как связать CommandParameter с неизвестным родителем

Проблема, что я не могу понять, как получить команды для отправки SelectedItem TreeView.

Параметр всегда равен нулю. Я попытался использовать относительные источники, шаблоны родителей и т. Д .; а также, ищет цель treeviewitem, и просто datacontext. Я также попытался отправить различные свойства этих элементов (а не только TreeView в SelectedItem). Кажется, я ничего не могу понять.

<Application.Resources> 
    <ContextMenu x:Key="ContextMenu.TreeView"> 
     <MenuItem 
      Header="Add Node" 
      Command="{Binding AddNodeCommand}" 
      CommandParameter="{Binding Path=SelectedItem, RelativeSource={RelativeSource AncestorType={x:Type TreeView}}}"></MenuItem> 
     <MenuItem 
      Header="Delete Node" 
      Command="{Binding DeleteNodeCommand}" 
      CommandParameter="{Binding Path=SelectedItem,RelativeSource={RelativeSource AncestorType={x:Type TreeView}}}"></MenuItem> 
    </ContextMenu> 
</Application.Resources> 

<UserControl ...> 
    <TreeView 
     x:Name="TaxonomyTree" 
     ItemsSource="{Binding Path=Tree}"   
     ContextMenu="{StaticResource ContextMenu.TreeView}"/> 
</UserControl> 

ответ

1

Try:

<ContextMenu x:Key="ContextMenu.TreeView"> 
    <MenuItem Command="{Binding AddNodeCommand}" 
      CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, 
                     AncestorType={x:Type ContextMenu}}, 
             Path=PlacementTarget.SelectedItem}" 
      Header="Add Node" /> 
    <MenuItem Command="{Binding DeleteNodeCommand}" 
      CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, 
                     AncestorType={x:Type ContextMenu}}, 
             Path=PlacementTarget.SelectedItem}" 
      Header="Delete Node" /> 
</ContextMenu> 

Contextmenu не является частью одного и того же дереве визуалов как TreeView он связывает с. Поэтому нам нужно использовать PlacementTarget для перехода на TreeView соответственно.

Смежные вопросы