0

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?

5
  • 1
    stackoverflow.com/a/48966829/1506454 Commented Jul 13, 2021 at 19:41
  • @ASh thank you, this answers my question. I did search for it, but judging from the question of your linked answer, I'd never find it. Commented Jul 13, 2021 at 19:44
  • 1
    Also note that DataContext="{Binding}" is redundant. Commented Jul 13, 2021 at 19:44
  • Wasn't aware of that. Thanks @Clemens. Commented Jul 13, 2021 at 19:47
  • 1
    @MaxPlay, many recurring issues don't have a good canonical post on stackoverflow. I just know that I have already answered smth like this and can find reference quickly Commented Jul 13, 2021 at 19:48

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.