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
Maybe use TemplateBinding?
Something like:
{TemplateBinding YourPropertyInTheDataTemplateContext}
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