从BindingExpression获取源属性类型 [英] Get source property type from BindingExpression

查看:144
本文介绍了从BindingExpression获取源属性类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出绑定表达式的源属性类型。我想这样做是因为我想使用 UpdateSourceExceptionFilter 可提供比通用的无法转换更有用的错误消息。

I am trying to find out the source property type of a binding expression. I want to do this because I want to use the UpdateSourceExceptionFilter to provide a more useful error message than just the generic "couldn’t convert".

在.NET 4.5中,我使用 ResolvedSource ResolvedSourcePropertyName 可以通过反射来获得像这样的源属性类型:

In .NET 4.5 I use ResolvedSource and ResolvedSourcePropertyName with reflection to get the source property type like this:

PropertyInfo sourceProperty = expr.ResolvedSource.GetType().GetProperty(expr.ResolvedSourcePropertyName);
Type propertyType = sourceProperty.PropertyType;

这很好用。但是这两个BindingExpression属性都是在.NET 4.5中引入的,而我仍在4.0(由于Windows XP不能真正更新)。

This works just fine. However both those BindingExpression properties were just introduced with .NET 4.5, and I’m still on 4.0 (can’t really update because of Windows XP).

在.NET 4.0中执行此操作的好方法?我考虑过使用反射或仅使用私有 Worker <获取内部 SourceItem SourcePropertyName 属性。 / code>来获取这些值,但我宁愿避免访问内部/私有属性或字段(而且我认为这还需要我对信任做点事?这有什么含义?)。

So is there a nice way to do this in .NET 4.0? I thought about getting the internal SourceItem and SourcePropertyName properties using reflection or just the private Worker to get those values but I would rather avoid to access internal/private properties or fields (and I think this would also require me to do something about trust? What implications are there?).

推荐答案

不太漂亮,但是无法使用私有方法:

Not too pretty, but without access to private methods:

string[] splits = expr.ParentBinding.Path.Path.Split('.');
Type type = expr.DataItem.GetType();
foreach (string split in splits) {
    type = type.GetProperty(split).PropertyType;
}

因此,我们能够解析源属性。

Thus, we are able to resolve the source property.

这篇关于从BindingExpression获取源属性类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆