我有一个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>
我之前扩展的代码无法创建动态标签,需要DrawingBoard
的对象来做一些事情。由于我使用ItemsSource,因此我只在SelectionChanged
事件中获得了Diagrams的对象。如何获取当前所选选项卡的ContentTemplate.DataTemplate
对象(DrawingBoard)?
答案 0 :(得分:0)
您必须遍历VisualTree。此类型只有一个子元素,即来自当前选项卡。
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;
};
}
}
}
答案 1 :(得分:0)
找到解决我问题的方法。解决方案由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;
}