And*_*kin 10 c# wpf properties path
我正在编写一个自定义控件,我有一个属性路径作为字符串(想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;
}
}
Run Code Online (Sandbox Code Playgroud)
创建一个具有object类型的依赖项属性的对象,使用属性路径作为路径设置绑定,并将任意对象设置为源.绑定将执行,您可以看到属性路径末尾有什么(如果有的话).这是我发现在代码中做这种事情的唯一方法.你可以编写一个可以跟随属性路径的递归反射引擎,但它已经完成了,我们在绑定时使用它.你花五分钟写:)