Vivek Saurav
Vivek Saurav

Reputation: 2275

DataContext is null for TabItem DataTemplate

I have a Tabcontrol

<TabControl TabStripPlacement="Left"  
            Grid.Row="1" 
            x:Name="TabControl"
            ItemsSource="{Binding SomeProperty}"
           ContentTemplateSelector="{StaticResource SomeDataSelector}">
    <TabControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Name}"/>
        </DataTemplate>
    </TabControl.ItemTemplate>
</TabControl>

Where i am calling a DataTemplateSelector

<UserControl.Resources>
    <DataTemplate x:Key="DefaultTemplate" >
        <TextBlock Text="Default" FontSize="72"></TextBlock>
    </DataTemplate>
    <DataTemplate x:Key="FirstViewDataTemplate">
        <local:FirstView HorizontalAlignment="Left"/>
    </DataTemplate>
    <DataTemplate x:Key="SecondViewDataTemplate">
        <local:SecondView HorizontalAlignment="Left" DataContext="{Binding}"/>
    </DataTemplate>
    <local:SomeDataSelector x:Key="SomeDataSelector" 
                            FirstViewDataTemplate="{StaticResource FirstViewDataTemplate}"
                            SecondViewDataTemplate="{StaticResource SecondViewDataTemplate}"/>
</UserControl.Resources>

But the DataContext for the SecondView is coming as null

I tried element binding also but didn't help

What am i missing?

Upvotes: 1

Views: 480

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249546

I can't reproduce the issue. I created am application with your sample code and the missing selector and it worked. When are you seeing the DataContext as null ? If it in in the constructor then that is expected as binding has not occurred yet.

You can handle DataContextChanged event if you want to be notified when the data context id available.

Upvotes: 1

Related Questions