我正在写一个自定义控件,我有一个属性路径作为字符串(想想comboBox.SelectedValuePath
)。
代码中为任意对象评估此字符串的最佳方式是什么?WPF我应该如何评估属性路径?
我明显可以自己解析它,但它是一个黑客,我想路径支持一切comboBox.SelectedValuePath
(一致性)。
结果(感谢阿兰穆赫兰):
不知道关于这样的表现,但我不为业绩在意现在。
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;
}
}
是否注意到当Result属性是类型对象时,Target中DependencyProperty的声明类型是IEnumerable? – dtm 2013-06-04 23:14:39
@dtm可能只是我的错误 - 发布中间版本而不是最终版本。不过那是很久以前的事了,我不记得了。如果我找到这个代码,我会纠正这个问题,否则如果你测试了它,请让我知道你的发现。 – 2013-06-04 23:47:48
我没有实现类似这样的依赖项属性和属性本身匹配的类型;然而,令人惊讶的是,它仍然有效,如果我用DepedencyProperty.Register中的Object代替IEnumerable。不知道该怎么做... – dtm 2013-06-05 19:58:17