WPF: Is it possible to get all elements that have a specific attached property set?

I created a custom property that should be set on some unrelated elements. The purpose of this attached property is to keep the width of all these elements the same. Therefore, when any of these elements changes width, it should update all other elements using this set of properties. I can track changes in the attached property through the "DP processed property handler" set via UIPropertyMetadata, so when any element changes the width, I get this notification. What I need to do is update all other elements that have this property attached.

So I was wondering, is it possible to do this? Is there a way to list all DependencyObject instances that have a specific attached property?

I assume this is a bit of advanced WPF stuff, but this is a very specific specific requirement in my WPF application.

+3
source share
1 answer

You can list the visual tree and check if a property is set for each of the elements. Something like that:

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));

The GetAllChildren () extension method is implemented as follows:

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;
        }
    }
}
+3
source

All Articles