【问题标题】:Is there a way to get a property value of an object using PropertyPath class?有没有办法使用 PropertyPath 类获取对象的属性值?
【发布时间】:2009-11-21 23:36:12
【问题描述】:

我想获取对象的嵌套属性的值(类似于 Person.FullName.FirstName)。我看到在.Net 中有一个名为PropertyPath 的类,WPF 在Binding 中用于类似目的。 有没有办法复用WPF的机制,还是我自己写一个。

【问题讨论】:

    标签: c# .net wpf


    【解决方案1】:

    重用 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 事件以支持读取更改的值。我希望这会有所帮助!

    【讨论】:

    • 你会如何写回那个属性?
    • 我刚刚更新了代码示例以包括更新目标。您只需要确保 Binding 是 TwoWay 并提供一个 setter。
    【解决方案2】:

    我看不出你不能重复使用它的任何原因。

    PropertyPath:

    实现一个数据结构 将属性描述为下面的路径 另一个财产,或低于拥有 类型。属性路径用于数据 绑定到对象和情节提要中 和动画的时间线。

    【讨论】:

      猜你喜欢
      • 2019-11-27
      • 1970-01-01
      • 2019-03-29
      • 2012-09-25
      • 2010-11-23
      • 2013-08-13
      • 2012-09-28
      • 1970-01-01
      • 2010-12-27
      相关资源
      最近更新 更多