Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从BindingExpression获取源属性类型_C#_.net_Reflection_.net 4.0 - Fatal编程技术网

C# 从BindingExpression获取源属性类型

C# 从BindingExpression获取源属性类型,c#,.net,reflection,.net-4.0,C#,.net,Reflection,.net 4.0,我试图找出绑定表达式的源属性类型。我之所以要这样做,是因为我想使用提供一条比一般的“无法转换”更有用的错误消息 在.NET 4.5中,我使用and和reflection来获取源属性类型,如下所示: PropertyInfo sourceProperty = expr.ResolvedSource.GetType().GetProperty(expr.ResolvedSourcePropertyName); Type propertyType = sourceProperty.PropertyTy

我试图找出绑定表达式的源属性类型。我之所以要这样做,是因为我想使用提供一条比一般的“无法转换”更有用的错误消息

在.NET 4.5中,我使用and和reflection来获取源属性类型,如下所示:

PropertyInfo sourceProperty = expr.ResolvedSource.GetType().GetProperty(expr.ResolvedSourcePropertyName);
Type propertyType = sourceProperty.PropertyType;
这个很好用。然而,这两个BindingExpression属性都是在.NET4.5中引入的,我仍然使用4.0(由于WindowsXP的原因,无法真正更新)


那么在.NET4.0中有没有一种很好的方法来实现这一点呢?我曾考虑过使用反射或仅使用私有的
工作者
来获取内部
SourceItem
SourcePropertyName
属性以获取这些值,但我宁愿避免访问内部/私有属性或字段(我认为这也需要我做一些关于信任的事情?有什么影响?)

不太漂亮,但无法访问私有方法:

string[] splits = expr.ParentBinding.Path.Path.Split('.');
Type type = expr.DataItem.GetType();
foreach (string split in splits) {
    type = type.GetProperty(split).PropertyType;
}
因此,我们能够解析源属性。

是一种独立于内部/私有.NET对象的解决方案

当从父控件使用
DataContext
时,属性
expr.ResolvedSource
null
,因此它将不有用

查找源类型的原因是什么


为什么不使用simple
String.Format(“Binding在路径{0}中有异常”,expr.ParentBinding.path.path??String.Empty)

我在代码中使用它来查找源属性类型

        BindingExpression bindingExpression = BindingOperations.GetBindingExpression(this, SelectedItemProperty);
        object s = bindingExpression?.ResolvedSource;
        string pn = bindingExpression?.ResolvedSourcePropertyName;

        var type = s?.GetType().GetProperty(pn)?.PropertyType;

如果我能假设所有路径都是这样的简单路径(现在就是这样),我想这是一个可以接受的解决方案。谢谢!我对绑定目标(组件)不感兴趣但是绑定源。我既不知道绑定目标,也不知道绑定应用到的属性,但我对它也不感兴趣;我从.Btw中获得BindingExpression。您的代码可以简化为
TextBox.TextProperty.PropertyType