简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM