如何绑定到其的ItemTemplate XAML一个HierarchicalDataTemplate的DataContext的? [英] How to bind to the DataContext of a HierarchicalDataTemplate from its ItemTemplate XAML?

查看:339
本文介绍了如何绑定到其的ItemTemplate XAML一个HierarchicalDataTemplate的DataContext的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的WPF的TreeView,我已经定义了一个 HierarchicalDataTemplate 。在其的ItemTemplate ,有一个按钮,其命令我需要绑定到父视图模型,这是的DataContext HierarchicalDataTemplate 或者,换句话说,其持有的集合<视图模型code>子项目 code>在下面的例子。在的ItemTemplate 自己的DataContext - 在子项目的 - 被用作 CommandParameter

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>

这又如何在XAML做只?

How can this be done in XAML only?

推荐答案

下面结合应该工作:

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

这将绑定到DataContext的Command属性(在你的情况下保存收集的子项目VM)相关联,它是当前的TreeViewItem的父的TreeViewItem。

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.

这篇关于如何绑定到其的ItemTemplate XAML一个HierarchicalDataTemplate的DataContext的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆