I have a UserControl named AddressTemplate, which contains a StackPanel with an assortment of Labels & Textboxes. What I need is a way to find the immediate ancestor/parent of one of the controls within the AddressTemplate. Essentially, I need a way to determine whether a given Textbox is inside the AddressTemplate, or instead is outside this UserControl and is just a standalone control.
What I’ve come up with so far is this:
private bool FindParent(Control target)
{
Control currentParent = new Control();
if (currentParent.GetType() == typeof(Window))
{
}
else if (currentParent.GetType() != typeof(AddressTemplate) && currentParent.GetType() != null)
{
currentParent = (Control)target.Parent;
}
else
{
return true;
}
return false;
}
The problem is, I keep getting an InvalidCastException because it can’t cast a StackPanel as a Control. Does anybody know the proper cast, or a viable way to fix this?
You probably want to use
LogicalTreeHelper.GetParenthere, which returns a DependencyObject:This would walk up the logical parent tree until it found no parent or the user control you are looking for. For more info, look at Trees in Wpf on MSDN