Reputation: 1673
I have a TabControl with two ContentTemplates:
<TabControl ItemsSource="{Binding Tabs}" ContentTemplateSelector="{StaticResource TabSelector}">
<TabControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding TabName}" HorizontalAlignment="Center" />
</StackPanel>
</DataTemplate>
</TabControl.ItemTemplate>
</TabControl>
And my two templates are two user controls:
<UserControl.Resources>
<ResourceDictionary>
<DataTemplate x:Key="UserListTemplate">
<uc:UserList />
</DataTemplate>
<DataTemplate x:Key="UserContentTemplate">
<uc:User />
</DataTemplate>
<uc:TabSelector x:Key="TabSelector" UserListTemplate="{StaticResource UserListTemplate}" UserContentTemplate="{StaticResource UserContentTemplate}" />
</ResourceDictionary>
</UserControl.Resources>
I'm setting the DataContext in the XAML:
<UserControl.DataContext>
<local:ViewUsers />
</UserControl.DataContext>
The TabControl bind is working, showing all the tabs as I add/remove from the collection, but how do I get the DataContext in my UserControls? The DataContext is always null when the UserControl is started.
Upvotes: 4
Views: 3413
Reputation: 31576
The binding issue for a template is that once rendered as individual control will, depending on the control find its parent's data context, not from the visual tree but from its logical tree.
So the best bet is bind to the visual parent's datacontext via a RelativeSource
direct binding such as:
{Binding TabName,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType={x:Type TabControl }}}
or more likely:
{Binding DataContext.TabName,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType={x:Type TabControl }}}
Upvotes: 3