有没有办法让使用的PropertyPath类的一个对象的属性值? [英] Is there a way to get a property value of an object using PropertyPath class?

查看:235
本文介绍了有没有办法让使用的PropertyPath类的一个对象的属性值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to get a value of a nested property of an object (something like Person.FullName.FirstName). I saw that in .Net there is a class named PropertyPath, which WPF uses for a similar purpose in Binding. Is there a way to reuse WPF's mechanism, or should I write one on my own.

推荐答案

重用的PropertyPath是诱人的,因为它支持遍历嵌套属性,你指出和索引。你可以自己编写类似的功能,我有我自己的过去,但它涉及到半复杂的文本分析和大量的反思工作。

Reusing the PropertyPath is tempting as it supports traversing nested properties as you point out and indexes. You could write similar functionality yourself, I have myself in the past but it involves semi-complicated text parsing and lots of reflection work.

正如安德鲁所指出的,你可以简单地重复使用WPF中的PropertyPath。我假设你只是想评估对,你在这种情况下,code是有点涉及的对象路径。为了评价它具有在结合针对的DependencyObject要使用的的PropertyPath。为了证明这一点,我刚刚创建了一个简单的DependencyObject称为BindingEvaluator其中有一个的DependencyProperty。真正神奇然后通过调用该应用的结合BindingOperations.SetBinding所以我们可以读出评估值发生。

As Andrew points out you can simply reuse the PropertyPath from WPF. I'm assuming you just want to evaluate that path against an object that you have in which case the code is a little involved. To evaluate the PropertyPath it has to be used in a Binding against a DependencyObject. To demonstrate this I've just created a simple DependencyObject called BindingEvaluator which has a single DependencyProperty. The real magic then happens by calling BindingOperations.SetBinding which applies the binding so we can read the evaluated value.

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事件来支持改变读数值。我希望这有助于!

If you wanted to extend this you could wire up the PropertyChanged events to support reading values that change. I hope this helps!

这篇关于有没有办法让使用的PropertyPath类的一个对象的属性值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆