How to enumerate all dependency properties of control?

前端 未结 5 1799
名媛妹妹
名媛妹妹 2020-12-01 21:17

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

5条回答
  •  甜味超标
    2020-12-01 22:09

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

提交回复
热议问题