WPF - 从绑定路径获取属性值

dev*_*tal 14 wpf binding markup-extensions

如果我有一个名为MyObject的对象,它有一个名为MyChild的属性,它本身有一个名为Name的属性.如果我拥有的只是一个绑定路径(即"MyChild.Name"),并且对MyObject的引用,我该如何获取该Name属性的值?

MyObject
  -MyChild
    -Name
Run Code Online (Sandbox Code Playgroud)

Tho*_*que 21

我找到了一种方法来做到这一点,但它非常难看,可能不是很快......基本上,我们的想法是创建一个给定路径的绑定并将其应用于依赖项对象的属性.这样,绑定完成了检索值的所有工作:

public static class PropertyPathHelper
{
    public static object GetValue(object obj, string propertyPath)
    {
        Binding binding = new Binding(propertyPath);
        binding.Mode = BindingMode.OneTime;
        binding.Source = obj;
        BindingOperations.SetBinding(_dummy, Dummy.ValueProperty, binding);
        return _dummy.GetValue(Dummy.ValueProperty);
    }

    private static readonly Dummy _dummy = new Dummy();

    private class Dummy : DependencyObject
    {
        public static readonly DependencyProperty ValueProperty =
            DependencyProperty.Register("Value", typeof(object), typeof(Dummy), new UIPropertyMetadata(null));
    }
}
Run Code Online (Sandbox Code Playgroud)