Get DependencyProperty by Name for WPF and Silverlight

Brian Lagunas / Tuesday, January 29, 2013

Have you ever needed to create bindings to elements without knowing, or having access to, their DependencyProperty until runtime?  Have you ever had the need to get the DependencyProperty of an element at runtime for any reason at all?  If so, then this code snippet may be of use to you.

public static DependencyProperty GetDependencyPropertyByName(DependencyObject dependencyObject, string dpName)
{
    return GetDependencyPropertyByName(dependencyObject.GetType(), dpName);
}

public static DependencyProperty GetDependencyPropertyByName(Type dependencyObjectType, string dpName)
{
    DependencyProperty dp = null;

    var fieldInfo = dependencyObjectType.GetField(dpName, BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);
    if (fieldInfo != null)
    {
        dp = fieldInfo.GetValue(null) as DependencyProperty;
    }

    return dp;
}

 

The usage is simple.  One method allows you to pass in the dependency object instance, plus the string representation of the DependencyProperty on the object.  The other method allows you to get a dependency object from a Type.  The most important thing to remember is the dpName parameter is the full name of the DependencyProperty as it is declared, not the property name you reference in code or XAML. 

Consider the following example:

var usingInstance = GetDependencyPropertyByName(_button, "ContentProperty");

var usingType = GetDependencyPropertyByName(typeof(Button), "ContentProperty");

 

As you can see, the dpName parameter is the actual DependencyProperty name (ContentProperty) and not the property name (Content).  Now that you have the DepedencyProperty, you can get all kinds of meta data about the property, and even creating dynamic data bindings.  I hope this is helpful.