我想得到一个对象的嵌套属性的值(比如person.fullname.firstname)。我在.net中看到了一个名为propertypath的类,wpf将其用于绑定中的类似用途。
有没有办法重用wpf的机制,或者我应该自己编写一个。

最佳答案

重用propertypath很诱人,因为它支持遍历您指出的嵌套属性和索引。您可以自己编写类似的功能,我以前也有过类似的功能,但它涉及到半复杂的文本解析和大量的反射工作。
正如andrew指出的那样,您可以简单地重用wpf中的propertypath。我假设您只是想根据您拥有的对象来计算该路径,在这种情况下,代码有点复杂。若要计算PropertyPath,必须在绑定DependencyObject时使用它。为了演示这一点,我刚刚创建了一个名为bindingEvaluator的简单dependencyObject,它有一个dependencProperty。真正的魔力是通过调用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事件以支持读取更改的值。我希望这有帮助!

09-26 01:58