通过PropertyPath获取房产

时间:2012-10-08 06:28:28

标签: .net data-binding

此论坛条目(http://stackoverflow.com/questions/2767557/wpf-get-property-that-a-control-is-bound-to-in-code-behind)提供以下声明以获取“从“DependencyProperty:

绑定到”PropertyPath from“
BindingExpression be = BindingOperations.GetBindingExpression((FrameworkElement)yourComboBox, ((DependencyProperty)Button.SelectedItemProperty));
string Name = be.ParentBinding.Path.Path; 

我想更进一步 - 从PropertyPath中找到DependencyProperty。有没有标准方法可以做到这一点?最终目标是在行为中使用它来删除现有绑定(AssociatedObject.PropertyPath到smth)并替换为两个(Behavior.Original到smth和AssociatedObject.PropertyPath到Behavior.Modified)。

1 个答案:

答案 0 :(得分:0)

您可以使用反射按名称获取依赖项属性:

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