I have a UserControl
'child' within another UserControl
(that's acting as a TabItem in a TabControl
). Between the child UserControl
and the TabItem ancestor are a number of other controls (eg: Grid
s, a StackPanel
, possibly a ScrollViewer
, etc).
I want to access a property of the TabItem UserControl
in my child UserControl
and customised a commonly suggested recursive function that walks up the Visual tree. However, this always returned true
at the first null check until I added a query on the Logical tree.
Code:
public MyTabItem FindParentTabItem(DependencyObject child)
{
DependencyObject parent = VisualTreeHelper.GetParent(child) ?? LogicalTreeHelper.GetParent(child);
// are we at the top of the tree
if (parent == null)
{
return null;
}
MyTabItem parentTabItem = parent as MyTabItem;
if (parentTabItem != null)
{
return parentTabItem;
}
else
{
//use recursion until it reaches the control
return FindParentTabItem(parent);
}
}
Unfortunately, this too returns null. When stepping through the method, I see it does find the correct UserControl
TabItem, but then as it recurses(?) back through the returns, it reverts this back to null which is then returned to the calling method (in the child UserControl
's Loaded event):
MyTabItem tab = FindParentTabItem(this);
How do I fix this so my method correctly returns the found MyTabItem
?