4

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”.

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;

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).

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?).

poke
  • 369,085
  • 72
  • 557
  • 602

3 Answers3

5

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.

Alex Butenko
  • 3,664
  • 3
  • 35
  • 54
  • I guess that would be an acceptable solution if I can assume that all paths are just simple paths like that (they are right now). Thanks! – poke May 22 '13 at 12:43
2

i use this in my code to find source property Type

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

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

Here is one solution that is independent from internal/private .NET objects.

Property expr.ResolvedSource is null when DataContext is used from parent control, so it will not be useful.

What is the reason to finding source type?

Why do not use simple String.Format("Binding has exception in path {0}", expr.ParentBinding.Path.Path?? String.Empty)?

Community
  • 1
  • 1
Artur A
  • 7,115
  • 57
  • 60
  • I’m not interested in the binding target (the component) but the binding source. And I know neither the binding target nor the property that the binding is applied to—but I’m not interested in it either; I get the BindingExpression from the [delegate](http://msdn.microsoft.com/en-us/library/system.windows.data.updatesourceexceptionfiltercallback.aspx). Btw. your code could be just simplified to `TextBox.TextProperty.PropertyType`. – poke May 22 '13 at 12:47