5
MainPage.xaml

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Grid x:Name="GridA">
        <Grid x:Name="GridB"/>
    </Grid>
</Grid>

It is possible get GridB parent from GridB

This is what I'm trying to do

//Null
Panel parent1 = GridB.Parent as Panel;

//Null
Panel parent2 = VisualTreeHelper.GetParent(GridB) as Panel;

All of them return null.

Any idea?

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
aiur
  • 649
  • 2
  • 7
  • 21

1 Answers1

10

Use VisualTreeHelper.GetParent method but as UIElement not Panel like this:

var parent = VisualTreeHelper.GetParent(GridB) as UIElement;
string pName = (parent as Grid).Name; //GridA
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
  • See also [here](https://stackoverflow.com/a/53202179/789423) for a method `FindAncestor(DependencyObject obj)`, which finds a parent element in more higher level. – Beauty Jul 07 '23 at 12:09