访问带有名称的数据模板

本文关键字:数据 有名称 访问 | 更新日期: 2023-09-27 18:03:24

我有许多TabItem,但在DataTemplate中只有一个DataGrid

现在我将访问DataGrid,因为我想更改内容…

<Window.Resources>
    <DataTemplate x:Key="ContentTabItem">
        <DataGrid Grid.Row="1" Name="_uiDataGrid"/>
    </DataTemplate>
</Window.Resources>
<Grid>
    <TabControl Name="_uiTabControl" SelectionChanged="_uiTabControl_SelectionChanged">
        <TabItem Name="_uiTabItembla1" Header="bla1" ContentTemplate="{StaticResource ResourceKey=ContentTabItem}"/>
        <TabItem Name="_uiTabItembla2" Header="bla2" ContentTemplate="{StaticResource  ResourceKey=ContentTabItem}"/>
    </TabControl>
</Grid>

我不能访问_uiDataGrid

访问带有名称的数据模板

试试这样做,从内容呈现者的内容模板中获取数据网格:

var contentPresenter = FindVisualChild<ContentPresenter>(_uiTabControl);
var dt = contentPresenter.ContentTemplate;
var datagrid = DataTemplateName.FindName("_uiDataGrid", contentPresenter) 
as DataGrid;

要找到可视子,请参考本stackoverflow帖子中提到的FindVisualChildren()FindVisualChild()函数

public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj)
       where T : DependencyObject
{
    if (depObj != null)
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
            if (child != null && child is T)
            {
                yield return (T)child;
            }
            foreach (T childOfChild in FindVisualChildren<T>(child))
            {
                yield return childOfChild;
            }
        }
    }
}
public static childItem FindVisualChild<childItem>(DependencyObject obj)
    where childItem : DependencyObject
{
    foreach (childItem child in FindVisualChildren<childItem>(obj))
    {
        return child;
    }
    return null;
}