我UserControl
在另一个中有一个“孩子” UserControl
(在 a 中充当 TabItem TabControl
)。在子UserControl
元素和 TabItem 祖先之间是许多其他控件(例如:Grid
s、a StackPanel
、可能是 aScrollViewer
等)。
我想UserControl
在我的孩子中访问 TabItem 的一个属性,UserControl
并自定义一个通常 建议的递归函数,该函数沿着 Visual 树向上走。但是,这总是true
在第一次空检查时返回,直到我在逻辑树上添加查询。
代码:
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);
}
}
不幸的是,这也返回 null。当单步执行该方法时,我看到它确实找到了正确的UserControl
TabItem,但是当它通过返回递归(?)返回时,它将它恢复为 null,然后返回给调用方法(在 childUserControl
的 Loaded 事件中):
MyTabItem tab = FindParentTabItem(this);
如何解决此问题,以便我的方法正确返回 found MyTabItem
?