0

I have a TabControl which looks like this:

<TabControl x:Name="TabControl" SelectedIndex="0" ItemsSource="{Binding Diagrams}" SelectionChanged="TabControl_OnSelectionChanged">
        <TabControl.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="Test">
                </TextBlock>
            </DataTemplate>
        </TabControl.ItemTemplate>
        <TabControl.ContentTemplate>
            <DataTemplate>
                <drawingBoard:DrawingBoard x:Name="TheDrawingBoard" DockPanel.Dock="Top" Focusable="True"/>
            </DataTemplate>
        </TabControl.ContentTemplate>
    </TabControl>

The code I extend previously was not able to create dynamic tabs and needs the object of the DrawingBoard to do some stuff. Since I use ItemsSource I only get an object of Diagrams in my SelectionChanged Event. How do I get the ContentTemplate.DataTemplate object (DrawingBoard) of my currently selected tab?

hullunist
  • 1,117
  • 2
  • 11
  • 31

2 Answers2

0

You have to iterate through VisualTree. There is only one child element of this Type, namely from current tab.

private void TabControl_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if ((sender as TabControl)!=null)
            {
                var yourCtl = GetChildren<DrawingBoard>((sender as TabControl)).FirstOrDefault() as DrawingBoard;
            }
        }

        IEnumerable<T> GetChildren<T>(FrameworkElement parent) where T : FrameworkElement
        {
            var chCount = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < chCount; i++)
            {
                var child = VisualTreeHelper.GetChild(parent, i);
                if (child is T)
                {   
                    yield return child as T;
                }
                if (child is FrameworkElement)
                {
                    foreach (var item in GetChildren<T>(child as FrameworkElement))
                    {
                        yield return item;
                    };
                }
            }
        }
Rekshino
  • 6,954
  • 2
  • 19
  • 44
0

Found a solution to my problem. Solution is by Dr. WPF.

private void TabControl_OnLoaded(object sender, RoutedEventArgs e)
    {
        TabControl tabControl = sender as TabControl;
        ContentPresenter cp =
            tabControl.Template.FindName("PART_SelectedContentHost", tabControl) as ContentPresenter;

        var db = tabControl.ContentTemplate.FindName("TheDrawingBoard", cp) as DrawingBoard;
        CurrentlySelectedDrawingBoard = db;
    }
hullunist
  • 1,117
  • 2
  • 11
  • 31