Get All The Attached DPs/DPs for An Object?

|

Someone asks on MSDN forum on how to get a list of all dependency/attached properties of an Object, Douglas Stockwell responds to it with an awesome reflection code on how to get all the dependency/attached properties defined by built-in WPF library classes, but his solution doesn't solve the original poster's problem, after examining the issue for a bit, I come up with my solution:

using System;
using System.Windows;
using System.Collections.Generic;
using System.Windows.Markup;
using System.Windows.Markup.Primitives;

namespace Sheva.Windows.Markup
{
public static class
MarkupHelper
{
///
<summary>
///
Gets a list of locally applied DPs on an element.
///
</summary>
public static List<DependencyProperty> GetDependencyProperties(Object element)
{
List<DependencyProperty> properties = new List<DependencyProperty>();
MarkupObject markupObject = MarkupWriter.GetMarkupObjectFor(element);
if (markupObject != null)
{
foreach (MarkupProperty mp in markupObject.Properties)
{
if (mp.DependencyProperty != null)
{
properties.Add(mp.DependencyProperty);
}
}
}

return properties;
}

///
<summary>
///
Gets a list of locally applied attached DPs on an element.
///
</summary>
public static List<DependencyProperty> GetAttachedProperties(Object element)
{
List<DependencyProperty> attachedProperties = new List<DependencyProperty>();
MarkupObject markupObject = MarkupWriter.GetMarkupObjectFor(element);
if (markupObject != null)
{
foreach (MarkupProperty mp in markupObject.Properties)
{
if (mp.IsAttached)
{
attachedProperties.Add(mp.DependencyProperty);
}
}
}

return attachedProperties;
}
}
}



As an aside, I really want to give my special thanks to Douglas Stockwell, his nifty VSPaste plugin for Live Writer makes my blogging experience much easier.

0 comments: