WPF我应该如何评估属性路径?

时间:2010-02-06 08:59:13

标签: c# wpf path properties

我正在编写一个自定义控件,我有一个属性路径作为字符串(想想comboBox.SelectedValuePath) 在代码中为任意对象计算此字符串的最佳方法是什么?

我显然可以自己解析它,但这是一个黑客攻击,我希望路径支持comboBox.SelectedValuePath所做的一切(为了保持一致)。

结果(感谢Aran Mulholland):

不确定这个的表现,但我现在对表现并不在意。

public class BindingEvaluator {
    #region Target Class

    private class Target : DependencyObject {
        public static readonly DependencyProperty ResultProperty = DependencyProperty.Register(
            "Result", typeof(IEnumerable), typeof(BindingEvaluator)
        );

        public object Result {
            get { return this.GetValue(ResultProperty); }
            set { this.SetValue(ResultProperty, value); }
        }
    }

    #endregion

    public object GetValue(object source, string propertyPath) {
        var target = new Target();
        BindingOperations.SetBinding(target, Target.ResultProperty, new Binding(propertyPath) {
            Source = source,
            Mode = BindingMode.OneTime
        });
        return target.Result;
    }
}

1 个答案:

答案 0 :(得分:6)

创建一个具有object类型的依赖项属性的对象,使用属性路径作为路径设置绑定,并将任意对象设置为源。绑定将执行,您可以看到属性路径末尾有什么(如果有的话)。这是我发现在代码中做这种事情的唯一方法。你可以编写一个可以跟随属性路径的递归反射引擎,但它已经完成了,我们在绑定时使用它。你花五分钟写一下:)

相关问题