Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enumerate all dependency properties of control?

I have some WPF control. For example, TextBox. How to enumerate all dependency properties of that control (like XAML editor does)?

like image 279
Dennis Avatar asked Jan 25 '11 13:01

Dennis


2 Answers

public IList<DependencyProperty> GetAttachedProperties(DependencyObject obj)
{
    List<DependencyProperty> result = new List<DependencyProperty>();

    foreach (PropertyDescriptor pd in TypeDescriptor.GetProperties(obj,
        new Attribute[] { new PropertyFilterAttribute(PropertyFilterOptions.All) }))
    {
        DependencyPropertyDescriptor dpd =
            DependencyPropertyDescriptor.FromProperty(pd);

        if (dpd != null)
        {
            result.Add(dpd.DependencyProperty);
        }
    }

    return result;
}

Found here: http://social.msdn.microsoft.com/Forums/en/wpf/thread/580234cb-e870-4af1-9a91-3e3ba118c89c

like image 73
Pavlo Glazkov Avatar answered Sep 20 '22 12:09

Pavlo Glazkov


Using reflection is not needed (and a bad idead IMHO) because the framework has already utility classes for this (but they're not obvious to find :-).

Here is an answer based on this article: Enumerate Bindings and the LocalValueEnumerator Structure

    public static IEnumerable<DependencyProperty> EnumerateDependencyProperties(this DependencyObject obj)
    {
        if (obj != null)
        {
            LocalValueEnumerator lve = obj.GetLocalValueEnumerator();
            while (lve.MoveNext())
            {
                yield return lve.Current.Property;
            }
        }
    }

Here is another answer based on this other article: Getting list of all dependency/attached properties of an Object that uses MarkupWriter.GetMarkupObjectFor Method.

    public static IEnumerable<DependencyProperty> EnumerateDependencyProperties(object element)
    {
        if (element != null)
        {
            MarkupObject markupObject = MarkupWriter.GetMarkupObjectFor(element);
            if (markupObject != null)
            {
                foreach (MarkupProperty mp in markupObject.Properties)
                {
                    if (mp.DependencyProperty != null)
                        yield return mp.DependencyProperty;
                }
            }
        }
    }

    public static IEnumerable<DependencyProperty> EnumerateAttachedProperties(object element)
    {
        if (element != null)
        {
            MarkupObject markupObject = MarkupWriter.GetMarkupObjectFor(element);
            if (markupObject != null)
            {
                foreach (MarkupProperty mp in markupObject.Properties)
                {
                    if (mp.IsAttached)
                        yield return mp.DependencyProperty;
                }
            }
        }
    }
like image 29
Simon Mourier Avatar answered Sep 20 '22 12:09

Simon Mourier