【发布时间】:2011-01-13 19:57:33
【问题描述】:
我正在编写一个自定义控件,并且我有一个字符串形式的属性路径(想想comboBox.SelectedValuePath)。
在代码中为任意对象评估此字符串的最佳方法是什么?
我显然可以自己解析它,但它是一个 hack,我希望路径支持 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;
}
}
【问题讨论】:
-
需要注意的是,当Result属性为object类型时,Target中DependencyProperty的声明类型为IEnumerable?
-
@dtm 可能只是我的错误——发布了中间版本而不是最终版本。然而那是很久以前的事了,我不记得了。如果我找到此代码,我会更正问题,否则,如果您对其进行了测试,请告诉我您的发现。
-
我确实为依赖属性和属性本身实现了类似的匹配类型;但是,令人惊讶的是,如果我用 IEnumerable 代替 DepedencyProperty.Register 中的 Object,它仍然有效。不知道该怎么做...
标签: c# wpf path properties