如何从ItemsControl.ItemTemplate中绑定到父DataTemplate [英] How to bind to parent DataTemplate from within an ItemsControl.ItemTemplate

查看:845
本文介绍了如何从ItemsControl.ItemTemplate中绑定到父DataTemplate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个容器类型控件,其中包含许多项目。容器控件具有定义的 DataTemplate ,它还包含一个 ItemsControl DataTemplate 。然而,项目需要绑定到容器控件中的东西。下面给出一个简化的例子:

 < DataTemplate DataType ={x:Type ContainerType}> 

<! - 显示容器内容 - >

< ItemsControl ItemsSource ={Binding Items,Mode = OneWay}>

< ItemsControl.ItemTemplate>
< DataTemplate DataType ={x:Type Item}>

<! - 显示项目内容 - >
< ComboBox Text =选择容器级别选项...
ItemsSource ={这里有什么?/>

< / DataTemplate>
< /ItemsControl.ItemTemplate>

< / ItemsControl>
< / DataTemplate>

如何将物品级别的东西绑定到容器级别?

解决方案

您可以使用 RelativeSource 绑定

 < ComboBox ItemsSource ={Binding SomeCollection,
RelativeSource = {RelativeSource
AncestorType = {x:Type local:MyContainerControl}}}/> ;

您用于绑定路径的内容取决于集合所在的位置。如果它位于 MyContainerControl 上的 DependencyProperty 中,则上述绑定工作正常。如果它位于 DataContext MyContainerControl 中,那么您需要将绑定路径设置为 DataContext.SomeCollection


I have a container type control which contains a number of items. The container control has a DataTemplate defined which also contains a ItemsControl with a DataTemplate for the item. The items however need to bind to something from the container control. A simplified example is given below:

<DataTemplate DataType="{x:Type ContainerType}">

    <!-- Display of the container stuff-->

    <ItemsControl ItemsSource="{Binding Items, Mode=OneWay}">

        <ItemsControl.ItemTemplate>
              <DataTemplate DataType="{x:Type Item}">

                  <!-- Display of the item stuff -->
                  <ComboBox Text="Choose a container-level option..."
                            ItemsSource="{WHAT GOES HERE?}"/>

                </DataTemplate>
         </ItemsControl.ItemTemplate>

      </ItemsControl>
</DataTemplate>

How to I bind something at the item level back up to the container level?

解决方案

You can use a RelativeSource binding

<ComboBox ItemsSource="{Binding SomeCollection, 
              RelativeSource={RelativeSource 
                  AncestorType={x:Type local:MyContainerControl}}}"/>

What you use for your binding path depends on where the collection is located. If it is located as a DependencyProperty on MyContainerControl, then the above binding works fine. If it is located in the DataContext of MyContainerControl, then you'll need to set the binding path to DataContext.SomeCollection

这篇关于如何从ItemsControl.ItemTemplate中绑定到父DataTemplate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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