Can I get the Type() of a bound object in C#/WPF (even if the bound value is null)?
I have a binding to an unknown source. All I have is the binding. I have no other way of 开发者_Go百科looking at the bound object. I need to figure out the Type for the bound object, even if the value is null (this is where my problem is).
I was evaluating the binding by binding to an object and then using the object as a way to get the Type, but I need to know the type even if the value is null.
For instance, I have a class like so:
public class Customer{
public string Name { get; set; }
public int Age { get; set; }
}
Now, if I have a WPF control bind to any of those properties (let's assume they are dependency properties) I would like to get the type of the property, even if the value is null.
So, I have a custom control that now has a Binding object that represents {Binding Name} for instance. How can I get the type of the "bound object" using C#?
Are you willing to use reflection to get access to non-public members? If so, I think Binding
has an internal method called CreateBindingExpression
that returns a BindingExpression
, which has a private member called _listener
of internal type PropertyPathListener
. That has an internal property called LeafType
, which I believe is what you're looking for.
It's messy, requires trust, and is subject to failure in future versions of the Framework, but it might be the only way to get what you're looking for.
It should just be a matter of doing
MyCustomControl.DataContext != null ? MyCustomControl.GetType() : default(Type);
If the value is null, there is no type to be gotten. If the binding is to a static resource defined in the App.xaml, you would literally have to parse the xaml file itself to find out the type, if it's defined in a class you would have to reflect it to find out the type.
If the binding is done in code, I don't think you can do this, because it could be bound to a null local variable which you wouldn't even be able to reflect out (or maybe you can but that would be way over my head). If the binding is defined in xaml, you could rationally parse out the xaml and try to follow the xaml path parsing the other xaml files and reflecting any properties for bindings that path into the code.
This would be an enormous pain and I am pretty certain whatever you're endgoal here is, could be accomplished without the ridiculous time this would take by doing something other than trying to identify the type even if it was null.
精彩评论