문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top