Silverlight: Finding Parent control
The problem the UserControl's parent is not the ChildWindow, its the
Grid inside the child window. You need to get the parent of the parent
of the UserControl to navigate to the ChildWindow:-
ChildWindow cw = (ChildWindow)((FrameworkElement)this.Parent).Parent;
However embedding this in your UserControl would bad practice, you would be stipulating to the consumer of your UserControl where the it can be sited. In the above case for the user control to work it would need to always be a direct child of the Layout root.
A better approach would be to search up the visual tree looing for a ChildWindow. I would use this helper method (actually I'd place this in a helper extensions static class but I'll keep it simple here).
private IEnumerable Ancestors()
{
DependencyObject current = VisualTreeHelper.GetParent(this);
while (current != null)
{
yield return current;
current = VisualTreeHelper.GetParent(current);
}
}
Now you can use LINQ methods to get the ChildWindow with:-
ChildWindow cw = Ancestors().OfType().FirstOrDefault();
This will find the first ancestor of your UserControl that happens to be ChildWindow. This allows your UserControl to be placed at any depth in the child windows XAML, it would still find the correct object.
ChildWindow cw = (ChildWindow)((FrameworkElement)this.Parent).Parent;
However embedding this in your UserControl would bad practice, you would be stipulating to the consumer of your UserControl where the it can be sited. In the above case for the user control to work it would need to always be a direct child of the Layout root.
A better approach would be to search up the visual tree looing for a ChildWindow. I would use this helper method (actually I'd place this in a helper extensions static class but I'll keep it simple here).
private IEnumerable Ancestors()
{
DependencyObject current = VisualTreeHelper.GetParent(this);
while (current != null)
{
yield return current;
current = VisualTreeHelper.GetParent(current);
}
}
Now you can use LINQ methods to get the ChildWindow with:-
ChildWindow cw = Ancestors().OfType().FirstOrDefault();
This will find the first ancestor of your UserControl that happens to be ChildWindow. This allows your UserControl to be placed at any depth in the child windows XAML, it would still find the correct object.
Comments
Post a Comment