简体   繁体   English

TabItem DataTemplate的DataContext为null

[英]DataContext is null for TabItem DataTemplate

I have a Tabcontrol 我有一个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 我在哪里打电话给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 但是SecondView的DataContext为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 ? 什么时候看到DataContext为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. 如果希望在数据上下文ID可用时收到通知,则可以处理DataContextChanged事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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