简体   繁体   English

获取ItemsSource的DataTemplate对象

[英]Get the DataTemplate Object of an ItemsSource

I have a TabControl which looks like this: 我有一个看起来像这样的TabControl:

<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. 我之前扩展的代码无法创建动态选项卡,并且需要DrawingBoard的对象来做一些事情。 Since I use ItemsSource I only get an object of Diagrams in my SelectionChanged Event. 由于我使用ItemsSource,因此我在SelectionChanged事件中仅获得一个Diagrams对象。 How do I get the ContentTemplate.DataTemplate object (DrawingBoard) of my currently selected tab? 如何获取当前所选选项卡的ContentTemplate.DataTemplate对象(DrawingBoard)?

You have to iterate through VisualTree. 您必须遍历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. 解决方案由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;
    }

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

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