简体   繁体   中英

Get the DataTemplate Object of an ItemsSource

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?

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;
                    };
                }
            }
        }

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;
    }

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