有没有办法使用PropertyPath类获取对象的属性值?

我想获得一个对象的嵌套属性的值(类似于Person.FullName.FirstName)。 我在.Net中看到有一个名为PropertyPath的类,WPF在Binding中使用了类。 有没有办法重用WPF的机制,或者我应该自己编写一个机制。

重用PropertyPath很有诱惑力,因为它支持在指出和索引时遍历嵌套属性。 您可以自己编写类似的function,我过去一直在使用它,但它涉及半复杂的文本解析和大量的reflection工作。

正如Andrew指出的那样,您可以简单地从WPF重用PropertyPath。 我假设您只想针对您拥有的对象评估该路径,在这种情况下代码有点涉及。 要评估PropertyPath,必须在针对DependencyObject的绑定中使用它。 为了certificate这一点,我刚刚创建了一个名为BindingEvaluator的简单DependencyObject,它有一个DependencyProperty。 然后通过调用应用绑定的BindingOperations.SetBinding来实现真正的魔法,这样我们就可以读取评估值。

var path = new PropertyPath("FullName.FirstName"); var binding = new Binding(); binding.Source = new Person { FullName = new FullName { FirstName = "David"}}; // Just an example object similar to your question binding.Path = path; binding.Mode = BindingMode.TwoWay; var evaluator = new BindingEvaluator(); BindingOperations.SetBinding(evaluator, BindingEvaluator.TargetProperty, binding); var value = evaluator.Target; // value will now be set to "David" public class BindingEvaluator : DependencyObject { public static readonly DependencyProperty TargetProperty = DependencyProperty.Register( "Target", typeof (object), typeof (BindingEvaluator)); public object Target { get { return GetValue(TargetProperty); } set { SetValue(TargetProperty, value); } } } 

如果您想扩展它,可以连接PropertyChanged事件以支持读取更改的值。 我希望这有帮助!

我没有看到任何你无法重复使用它的原因。

PropertyPath

实现一个数据结构,用于将属性描述为另一个属性下面的路径,或者低于拥有类型。 属性路径用于绑定到对象的数据,以及用于动画的故事板和时间轴。