您可以枚举可视化树并检查是否在每个元素上设置了属性。像这样的东西:
var objectsWithPropertySet = new List<DependencyObject>();
if (RootVisual.ReadLocalValue(FocusIdProperty) != DependencyProperty.UnsetValue)
objectsWithPropertySet.Add(RootVisual);
objectsWithPropertySet.AddRange(RootVisual.GetAllChildren()
.Where(o => o.ReadLocalValue(FocusIdProperty) != DependencyProperty.UnsetValue));
GetAllChildren() 扩展方法是这样实现的:
public static class VisualTreeHelperExtensions
{
public static IEnumerable<DependencyObject> GetAllChildren(this DependencyObject parent)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
// retrieve child at specified index
var directChild = (Visual)VisualTreeHelper.GetChild(parent, i);
// return found child
yield return directChild;
// return all children of the found child
foreach (var nestedChild in directChild.GetAllChildren())
yield return nestedChild;
}
}
}