【发布时间】:2009-11-21 23:36:12
【问题描述】:
我想获取对象的嵌套属性的值(类似于 Person.FullName.FirstName)。我看到在.Net 中有一个名为PropertyPath 的类,WPF 在Binding 中用于类似目的。 有没有办法复用WPF的机制,还是我自己写一个。
【问题讨论】:
我想获取对象的嵌套属性的值(类似于 Person.FullName.FirstName)。我看到在.Net 中有一个名为PropertyPath 的类,WPF 在Binding 中用于类似目的。 有没有办法复用WPF的机制,还是我自己写一个。
【问题讨论】:
重用 PropertyPath 很诱人,因为它支持在您指出和索引时遍历嵌套属性。你可以自己编写类似的功能,我以前也有过,但它涉及半复杂的文本解析和大量的反射工作。
正如 Andrew 指出的那样,您可以简单地重用 WPF 中的 PropertyPath。我假设您只想针对您拥有的对象评估该路径,在这种情况下,代码有点涉及。要评估 PropertyPath,必须在针对 DependencyObject 的绑定中使用它。为了证明这一点,我刚刚创建了一个名为 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 事件以支持读取更改的值。我希望这会有所帮助!
【讨论】:
【讨论】: