微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – WPF如何评估属性路径?

我正在编写一个自定义控件,我有一个属性路径作为字符串(认为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对象的依赖关系属性,将其上的绑定设置为属性路径作为路径,并将任意对象作为源.绑定将执行,您可以看到属性路径的末尾(如果有的话).这是我发现在代码中做这种事情的唯一方法.你可以编写一个可以跟踪属性路径的递归反射引擎,但是它已经完成了,我们在绑定时使用它.带你五分钟写:)

原文地址:https://www.jb51.cc/csharp/93860.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐