我正在编写一个自定义控件,并且我有一个字符串形式的属性路径(想想
comboBox.SelectedValuePath
)。
在代码中,为任意对象计算该字符串的最佳方法是什么?
显然,我可以自己分析它,但这是一个黑客,我希望路径支持一切
组合框.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;
}
}