2

This forum entry (http://stackoverflow.com/questions/2767557/wpf-get-property-that-a-control-is-bound-to-in-code-behind) gives the following statements to get "bound to" PropertyPath from "bound from" DependencyProperty:

BindingExpression be = BindingOperations.GetBindingExpression((FrameworkElement)yourComboBox, ((DependencyProperty)Button.SelectedItemProperty));
string Name = be.ParentBinding.Path.Path; 

I want to go one step further - find the DependencyProperty from that PropertyPath. Is there any standard method to do that? The ultimate goal is to use it in a Behavior to remove the existing binding (AssociatedObject.PropertyPath to smth) and replace with two (Behavior.Original to smth and AssociatedObject.PropertyPath to Behavior.Modified).

MikNik
  • 84
  • 7

1 Answers1

0

You can get the dependency property by name using reflection:

public static class ReflectionHelper
{

    public static DependencyProperty GetDependencyProperty(this FrameworkElement fe, string propertyName)
    {
        var propertyNamesToCheck = new List<string> { propertyName, propertyName + "Property" };
        var type = fe.GetType();
        return (from propertyname in propertyNamesToCheck
                select type.GetPublicStaticField(propertyname)
                    into field
                    where field != null
                    select field.GetFieldValue<DependencyProperty>(fe))
            .FirstOrDefault();
    }

    public static FieldInfo GetPublicStaticField(this Type type, string fieldName)
    {
        return type.GetField(fieldName, BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Static);
    }
}
Benjamin
  • 1,165
  • 7
  • 19