views:

500

answers:

3

Hello, so I have this UserControl that's inside of another UserControl. Lets call them ParentUC and ChildUC. I need to get ParentUC from ChildUC.

I know to get the window owner would be Window.GetWindow(userControl), but UserControl doesn't have a method like this AFAIK.

Thanks for the help!

A: 

You can always use VisualTreeHelper.GetParent(child) to return the parent in the Visual Tree (the parent user control from a nested user control).

Reed Copsey
I did that but it gets the grid that contains the control, that's the reason I had to loop until it gets the first UserControl in the logical tree. And I think it's better to use the LogicalTreeHelper so the loop doesn't get into the templates, adorners, etc. Thanks for the suggestion.
Carlo
+1  A: 

I came up with this solution, but post if you have a better one. Thanks!

DependencyObject ucParent = this.Parent;

while (!(ucParent is UserControl))
{
    ucParent = LogicalTreeHelper.GetParent(ucParent);
}
Carlo
A: 

UserControl has a .Parent property that should give you access to it's parent.

Then you can cast it to your ParentUC object.

Scott
Yes, the problem is that the UserControl might be inside of a StackPanel, that is inside of a Grid, that is inside of the parent UserControl, in which case myUserControl.Parent will be a StackPanel, myUserControl.Parent.Parent would be a Grid, and finally myUserControl.Parent.Parent.Parent (lol of course this is simplified by not casting the parent to StackPanel or Grid) would be the UserControl. That's why I use the loop to get the first UserControl found on top of the child one.
Carlo
Haha, I saw the solution you had posted (not realizing that you had asked the question as well) and since the question appeared (to me) to indicate that the ChildUC was a direct child of ParentUC, I wanted to provide a more simple answer. Given the additional information to your scenario, I think the solution you came up with is what you need to do.
Scott
Yeah seems so. Somewhere I read that's what Window.GetWindow(UIElement) does, so I guess that's the best bet. Thanks for the suggestion though!
Carlo