WPF我应该如何评估一个属性路径? [英] WPF How should I evaluate a property path?
问题描述
我写一个自定义的控制,我有一个属性路径字符串(想想 comboBox.SelectedValuePath
)。结果
什么是最好的办法在代码,以计算这个字符串的任意对象?
我明明可以直接解析它自己,但它是一个黑客,我想的路径,支持一切 comboBox.SelectedValuePath
不同(一致性)
结果(感谢阿兰穆赫兰):
不知道关于这样的表现,但我不为演出不在乎多少现在。
公共类BindingEvaluator {
#地区的目标类
私有类目标:{的DependencyObject
公共静态只读的DependencyProperty ResultProperty = DependencyProperty.Register(
结果的typeof(IEnumerable的)的typeof(BindingEvaluator)
);
公共对象结果{
{返回this.GetValue(ResultProperty); }
集合{this.SetValue(ResultProperty,值); }
}
}
#endregion
公共对象的GetValue(对象源,字符串的PropertyPath){
VAR的目标=新目标( );
BindingOperations.SetBinding(目标,Target.ResultProperty,新的Binding(的PropertyPath){
来源=源,
模式= BindingMode.OneTime
});
返回target.Result;
}
}
创建有类型的对象,一个依赖属性的对象,设定你的财产路径的路径,你作为源任意对象就可以了绑定。绑定将执行,你可以看到什么(如果有的话)是在财产路径的末尾。这是我发现做这种事情在代码的唯一途径。你可以写,可以追随属性路径的递归反射引擎,但它已经完成,我们使用它时,我们绑定。带你五分钟写:)
I am writing a custom control, and I have a property path as string (think comboBox.SelectedValuePath
).
What is the best way in code to evaluate this string for a arbitrary object?
I obviously can just parse it myself, but it is a hack, and I want the path to support everything comboBox.SelectedValuePath
does (for consistency).
Result (thanks to Aran Mulholland):
Not sure about performance of this, but I do not care much for the performance right now.
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;
}
}
Create an object that has one dependency property of type object, set the binding on it with your property path as the path, and your arbitrary object as the source. the binding will execute and you can see what (if anything) is at the end of the property path. This is the only way i have found to do this kind of thing in code. you could write a recursive reflection engine that could follow a property path, but its already been done, we use it when we bind. take you five minutes to write :)
这篇关于WPF我应该如何评估一个属性路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!