我有一个带有孩子作为网格的枢轴。我正在尝试在枢轴选择更改时找到该网格。我的代码是这样的
<Pivot x:Name="mainContentPivot" SelectionChanged="mainContentPivot_SelectionChanged" ItemsSource="{x:Bind viewModel.headerElement, Mode=OneWay}" >
<Pivot.HeaderTemplate>
<DataTemplate x:DataType="models:HeaderUIModel">
<TextBlock Text="{Binding Name, Mode=OneWay}"/>
</DataTemplate>
</Pivot.HeaderTemplate>
<Pivot.ItemTemplate>
<DataTemplate>
<Grid Name="grd">
</Grid>
</DataTemplate>
</Pivot.ItemTemplate>
</Pivot>
private void mainContentPivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
PivotItem item = (sender as Pivot).ContainerFromItem((sender as Pivot).SelectedItem) as PivotItem;
var gridView = FindElementInVisualTree<GridView>(item);
}
private T FindElementInVisualTree<T>(DependencyObject parentElement) where T : DependencyObject
{
var count = VisualTreeHelper.GetChildrenCount(parentElement);
if (count == 0) return null;
for (int i = 0; i < count; i++)
{
var child = VisualTreeHelper.GetChild(parentElement, i);
if (child != null && child is T)
return (T)child;
else
{
var result = FindElementInVisualTree<T>(child);
if (result != null)
return result;
}
}
return null;
}
在选定项目更改时,我总是将 gridView 设为 NULL。我在这里做错了什么?