2

此论坛条目(http://stackoverflow.com/questions/2767557/wpf-get-property-that-a-control-is-bound-to-in-code-behind)给出了以下语句以获得“绑定到”来自“绑定自”DependencyProperty 的 PropertyPath:

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

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

4

1 回答 1

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);
    }
}
于 2013-12-18T13:17:28.667 回答