I have a TabControl
that is populated via its ItemSource
property and I want the DataTemplate
for the TabControl.ContentTemplate
to create a UserControl
for the view models inside the bound ItemSource
.
Let's bring some code in to illustrate my problem.
I reduced everything to a minimum to avoid any cluttering when reading it. I am aware that this would not build.
The XAML code for the window:
<Window>
<Window.DataContext>
<OuterViewModel/>
</Window.DataContext>
<TabControl ItemsSource="{Binding Tabs}">
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Header}" />
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<DataTemplate>
<controls:CustomControl DataContext="{Binding}"/>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
</Window>
It's viewmodel (the ViewModelBase
is similar to this)
public class OuterViewModel : ViewModelBase
{
// This would get populated in the constructor, don't worry about it here
public List<InnerViewModel> Tabs { get; } = new List<InnerViewModel>();
}
The inner viewmodel
public class InnerViewModel : ViewModelBase
{
private readonly DataClass data;
public InnerViewModel()
{
data = new DataClass() { Name = "null" };
}
public InnerViewModel(DataClass data)
{
this.data = data;
}
public string Header => data.Name;
public class DataClass
{
public string Name { get; set; }
}
}
The user control xaml
<UserControl x:Class="CustomControl">
<UserControl.DataContext>
<InnerViewModel/>
</UserControl.DataContext>
<Grid>
<TextBlock Text="{Binding Header}"/>
</Grid>
</UserControl>
I expected to see the text in the content to be the same as the header, but the DataContext was not updated via the binding. When I remove the DataContext definition in the user controls XAML it works, but I want it at design time.
How can I achieve this?