Pregunta

In my WPF TreeView, I have defined a HierarchicalDataTemplate. In its ItemTemplate, there is a button whose Command I need to bind to the parent ViewModel, this is the DataContext of the parent HierarchicalDataTemplate or, in other words, the ViewModel which holds the collection SubItems in the example below. The ItemTemplates own DataContext - the SubItem - is to be used as the CommandParameter.

<TreeView ItemsSource="{Binding Items}">
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding SubItems}">                
            <HierarchicalDataTemplate.ItemTemplate>
                <DataTemplate>
                    <Button Command="??CmdOnDtaCntxtOfHierDtaTmplt" 
                            CommandParameter="{Binding}" />                                 
                </DataTemplate>
            </HierarchicalDataTemplate.ItemTemplate>
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

How can this be done in XAML only?

¿Fue útil?

Solución

The following binding should work:

<Button Command="{Binding DataContext.Command, 
        RelativeSource={RelativeSource AncestorLevel=2, AncestorType=TreeViewItem}}"
        CommandParameter="{Binding}" />

This will bind to the Command property of the DataContext (in your case the VM that holds the collection SubItems) associated to the TreeViewItem that is the parent of the current TreeViewItem.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top