【问题标题】:Get source property type from BindingExpression从 BindingExpression 获取源属性类型
【发布时间】:2013-05-21 13:47:42
【问题描述】:

我正在尝试找出绑定表达式的源属性类型。我想这样做是因为我想使用UpdateSourceExceptionFilter 来提供比一般的“无法转换”更有用的错误消息。

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

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

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

那么在 .NET 4.0 中是否有一个很好的方法来做到这一点?我考虑过使用反射来获取内部SourceItemSourcePropertyName 属性,或者只使用私有Worker 来获取这些值,但我宁愿避免访问内部/私有属性或字段(我认为这也需要我对信任做点什么?有什么影响?)。

【问题讨论】:

    标签: c# .net reflection .net-4.0


    【解决方案1】:

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

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

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

    【讨论】:

    • 如果我可以假设所有路径都只是这样的简单路径(它们现在是),我想这将是一个可接受的解决方案。谢谢!
    【解决方案2】:

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

            BindingExpression bindingExpression = BindingOperations.GetBindingExpression(this, SelectedItemProperty);
            object s = bindingExpression?.ResolvedSource;
            string pn = bindingExpression?.ResolvedSourcePropertyName;
    
            var type = s?.GetType().GetProperty(pn)?.PropertyType;
    

    【讨论】:

      【解决方案3】:

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

      DataContext 从父控件使用时,属性 expr.ResolvedSourcenull,因此它不会有用。

      查找源类型的原因是什么?

      为什么不用简单的String.Format("Binding has exception in path {0}", expr.ParentBinding.Path.Path?? String.Empty)

      【讨论】:

      • 我对绑定目标(组件)不感兴趣,但对绑定源感兴趣。而且我既不知道绑定目标也不知道绑定应用到的属性——但我也不感兴趣;我从delegate 得到 BindingExpression。顺便提一句。您的代码可以简化为TextBox.TextProperty.PropertyType
      猜你喜欢
      • 2020-01-29
      • 2021-12-04
      • 1970-01-01
      • 1970-01-01
      • 2019-09-28
      • 1970-01-01
      • 2013-01-04
      • 2021-07-16
      • 1970-01-01
      相关资源
      最近更新 更多