我想要获取一个对象的嵌套属性的值(类似于Person.FullName.FirstName)。我看到在.Net中有一个名为PropertyPath的类,它在绑定中用于类似的目的。有没有办法重用WPF的机制,或者我应该自己写一个。
发布于 2009-05-18 12:56:29
重用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事件连接起来,以支持读取更改的值。我希望这能帮到你!
发布于 2009-05-18 11:14:50
我看不出你有什么理由不能重用它。
请参阅PropertyPath
实现了一种数据结构,用于将属性描述为另一个属性或所属类型下的路径。属性路径用于对象的数据绑定,以及动画的情节提要和时间线中。
https://stackoverflow.com/questions/877171
复制相似问题