Reputation: 13
I have a collection of Barcodes that contains a collection of Positions. How do I set the DataContext of a custom control to a Position item in the collection?
<TreeView ItemsSource="{Binding SelectedPlate.Barcodes}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Positions}"
DataType="{x:Type ControlViewModels:BarcodeViewModel}">
<TextBox Text="{Binding Code}"/>
<HierarchicalDataTemplate.ItemTemplate>
<DataTemplate>
<!--The Custom Control that needs to bind to the Position item-->
<ControlViews:PositionControl DataContext="{Binding}"/>
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
Upvotes: 1
Views: 138
Reputation: 169200
The root element in the ItemTemplate
inherits the DataContext
so you can remove DataContext="{Binding}"
.
<TreeView ItemsSource="{Binding SelectedPlate.Barcodes}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Positions}"
DataType="{x:Type ControlViewModels:BarcodeViewModel}">
<TextBox Text="{Binding Code}"/>
<HierarchicalDataTemplate.ItemTemplate>
<DataTemplate>
<ControlViews:PositionControl />
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
In the PositionControl
you can then bind directly to a public property of a Position
object assuming you don't explicitly set the DataContext
of the control somewhere.
Upvotes: 1