Kai
Kai

Reputation: 1477

Get instantiated UIElement of ContentTemplate from TabControl

I have a TabControl where the ContentTemplate is defined by a DataTemplate containing a ContentPresenter. The mapping UIElement class is defined by a DataTemplate for the specific ViewModel type. It works like that:

<UserControl.Resources>
        <DataTemplate DataType="{x:Type ViewModels:DiagramVM}">
            <Controls:Diagram DataContext="{Binding}" x:Name="diagram"/>
        </DataTemplate>
</UserControl.Resources>

<TabControl ItemsSource="{Binding Path=Tabs, Mode=TwoWay}" SelectedIndex="{Binding Path=SelectedTabIndex}"
                            x:Name="AnalysisTabCtrl" Template="{DynamicResource ScrollableTabControlTemplate}">
    <TabControl.ItemTemplate>
                    <DataTemplate>
                        <Label Content="{Binding Path=Header}"/>
                    </DataTemplate>
    </TabControl.ItemTemplate>
    <TabControl.ContentTemplate>
                    <DataTemplate>
                        <ContentPresenter Content="{Binding Path=ViewModel}"/>
                    </DataTemplate>
    </TabControl.ContentTemplate>
 </TabControl>

My problem is that I need the instance of the instantiated UIElements. In this case the Diagram instances. How can I get them?

Upvotes: 0

Views: 1171

Answers (1)

brunnerh
brunnerh

Reputation: 184526

You can use the ItemsControl.ItemContainerGenerator to get a TabItem out of your TabControl, then you can use FindName on the TabItem.ContentTemplate to search for named instantiated controls. (Here you would probably need to name the content-presenter and then again search in its ContentTemplate)

I would not recommend doing anything like that, if you cannot manage without this you probably did not bind all the relevant properties to your items.

Upvotes: 1

Related Questions