How to bind to the DataContext of a HierarchicalDataTemplate from its ItemTemplate XAML?

故事扮演 提交于 2019-12-02 07:20:32

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/16166152/how-to-bind-to-the-datacontext-of-a-hierarchicaldatatemplate-from-its-itemtempla

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!