how to get the name of a grid in datatemplate of a gridview.


  • hi,

    how to get the name of a grid in data template of a gridview while loading the child page with this grid to mainpage . I need this grid in mainpage.

    the xaml is as follows.



    GridView x:Name="contactsGridview_"  " AllowDrop="True">


    <DataTemplate >

    <Grid x:Name="itemGrid_" Height="70" Width="275" Background="Red">


    <ColumnDefinition Width="Auto"/>

    <ColumnDefinition Width="*"/>


    <Image Source="Assets/contactpic.png"  Width="50"/>

    <StackPanel Margin="55,5,0,0">

    <TextBlock >

    <TextBlock >




    </GridView.ItemTemplate></GridView> iam tried with the below codebut its returns null value when its load to the mainpage.safe_cast<GridView^>(childPage->FindName("itemGrid_")); where childPage containing contants of the childPage....But the problem is that CGrid returns null value..Please help me if any idea about this..?

    Wednesday, September 5, 2012 7:35 AM


  • Hello,

    You should traversal visual tree to find the gird items and then compare the name in your function.

    Please follow these codes.

    Windows::UI::Xaml::FrameworkElement^ FindVisualChildByName(DependencyObject^ obj, String^ name)
    	FrameworkElement^ ret ;
    	int numChildren = VisualTreeHelper::GetChildrenCount(obj);
    	 for (int i = 0; i < numChildren; i++)
                    auto objChild = VisualTreeHelper::GetChild(obj, i);
                    auto child = safe_cast<FrameworkElement^>(objChild);
    				if (child != nullptr && child->Name == name)
                        return child;
                    ret = FindVisualChildByName(objChild, name);
    				if (ret != nullptr)
                return ret;
    template<typename ChildControl >
    ChildControl^ FindVisualChild (DependencyObject^ DependencyObj)
    	 for (int i = 0; i < VisualTreeHelper::GetChildrenCount(DependencyObj); i++)
                    DependencyObject^ Child = VisualTreeHelper::GetChild(DependencyObj, i);
    				if (Child != nullptr && Child->GetType()==ChildControl::GetType())
                        return safe_cast<ChildControl^>(Child);
                        ChildControl^ ChildOfChild = FindVisualChild(Child);
    					if (ChildOfChild != nullptr)
                            return ChildOfChild;
    	 return nullptr;
    void animateitem::MainPage::Button_Click_1(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
    	GridViewItem^ gridviewitem=safe_cast<GridViewItem^>(mygrid->ItemContainerGenerator->ContainerFromItem(mygrid->Items->GetAt(1)));
    	Grid^ grid=safe_cast<Grid^>(FindVisualChildByName(gridviewitem,"itemGrid_"));
    	grid->Background= ref new SolidColorBrush(Windows::UI::Colors::Black);

    Best regards,

    Jesse Jiang [MSFT]
    MSDN Community Support | Feedback to us

    • Marked as answer by Jesse Jiang Wednesday, September 12, 2012 2:10 AM
    Monday, September 10, 2012 12:04 PM