在子部分datatemplate上访问网格视图

时间:2014-12-08 15:14:00

标签: c# xaml windows-8.1

如何在“hub_my”的数据模板上访问“grid_my”?

<HubSection x:Name="hub_my" DataContext="{Binding my}">
            <DataTemplate>
                <GridView
                    x:Name="grid_my"
                    ItemsSource="{Binding Items}"
                    SelectionMode="Multiple"
                    SelectionChanged="grid_SelectionChanged"
                    Loaded="grid_Loaded">
                 </GridView>
            </DataTemplate>
        </HubSection>

1 个答案:

答案 0 :(得分:1)

试试这个:

private DependencyObject FindChildControl<T>(DependencyObject control, string ctrlName)
{
    int childNumber = VisualTreeHelper.GetChildrenCount(control);
    for (int i = 0; i < childNumber; i++)
    {
        DependencyObject child = VisualTreeHelper.GetChild(control, i);
        FrameworkElement fe = child as FrameworkElement;
        // Not a framework element or is null
        if (fe == null) return null;

        if (child is T && fe.Name == ctrlName)
        {
            // Found the control so return
            return child;
        }
        else
        {
            // Not found it - search children
            DependencyObject nextLevel = FindChildControl<T>(child, ctrlName);
            if (nextLevel != null)
                return nextLevel;
        }
    }
    return null;
}

然后你就可以得到你的GridView:

GridView myGrid = FindChildControl<GridView>(hub_my, "grid_my") as GridView;