c# – WPF如何评估属性路径?
发布时间:2020-12-15 03:44:38 所属栏目:百科 来源:网络整理
导读:我正在编写一个自定义控件,我有一个属性路径作为字符串(认为comboBox.SelectedValuePath). 为任意对象评估此字符串的代码中最好的方法是什么? 我显然可以自己解析,但它是一个黑客,我希望路径支持comboBox.SelectedValuePath的一切(为了一致性). 结果(感谢Ar
我正在编写一个自定义控件,我有一个属性路径作为字符串(认为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; } } 解决方法
创建一个对象,该对象具有一个type对象的依赖关系属性,将其上的绑定设置为属性路径作为路径,并将任意对象作为源.绑定将执行,您可以看到属性路径的末尾(如果有的话).这是我发现在代码中做这种事情的唯一方法.你可以编写一个可以跟踪属性路径的递归反射引擎,但是它已经完成了,我们在绑定时使用它.带你五分钟写:)
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |