我有以下实现来获取类型 T 的 VisualTree 中的所有子项:
IEnumerable<T> FindVisualChildrenRecurse<T>(DependencyObject root) where T : DependencyObject
{
if (root != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(root); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(root, i);
if (child != null && child is T)
{
yield return (T)child;
}
foreach (T childOfChild in FindVisualChildrenRecurse<T>(child))
{
yield return childOfChild;
}
}
}
}
我使用以下方法调用此方法:
IEnumerable<TextBlock> textBlocks = FindVisualChildren<TextBlock>(
button.Content as DependencyObject);
但是,当根依赖对象的类型为 T 时,此实现无法正常工作。假设我们想要在 VisualTree 中查找所有 TextBlock
Content
StackPanel
TextBlock
Image
在这种情况下,实现成功地找到了 TextBlock。但是,如果我有这个其他布局:
Content
TextBlock
该实现不包括根对象,因此它找不到 TextBlock。如何重新编写方法并包含根对象?