![](/img/trans.png)
[英]How to access a property path of each object in ItemsSource of a ListView from a DataTemplate
[英]Get the DataTemplate Object of an ItemsSource
我有一個看起來像這樣的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)?
您必須遍歷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;
};
}
}
}
找到了解決我問題的方法。 解決方案由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.