How to bind to parent DataTemplate from within an ItemsControl.ItemTemplate

青春壹個敷衍的年華 提交于 2019-12-06 11:46:05

问题


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?


回答1:


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




回答2:


Maybe use TemplateBinding?

Something like:

{TemplateBinding YourPropertyInTheDataTemplateContext}



回答3:


I've always been a big fan of ElementName. Basically you make sure you name the outer level control like : x:Name="MainWin" and then you can do something like this:

<DataTemplate>
        <StackPanel Orientation="Horizontal">
                <ComboBox ItemsSource="{Binding ElementName=MainWin, Path=DataContext.SomeCollection}"/>


来源:https://stackoverflow.com/questions/8184972/how-to-bind-to-parent-datatemplate-from-within-an-itemscontrol-itemtemplate

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