How to use reflection to get the BindingExpression (and value) for controls having a ContentProperty in Silverlight

StackOverflow https://stackoverflow.com/questions/2496238

Question

I need to use reflection to get the binding value in a control that is a DataGridTemplateColumn (e.g HyperLinkButton). Does anyone know how I might do this?

It seems simple enough to do this with a TextBlock because it has a TextProperty dependency property, but I can’t seem to get a binding expression from a control that does not have an immediate TextProperty. Here is the code I’m using to acquire the binding expression for a TextBlock:

FrameworkElement fe = (FrameworkElement)dependencyObj;
FieldInfo fi = fe.GetType().GetField("TextProperty");
BindingExpression bindingExpression = fe.GetBindingExpression((DependencyProperty)fi.GetValue(null))

However, the following code never works for a dependency object that is a HyperLinkButton:

FieldInfo fi = fe.GetType().GetField("ContentProperty");

Does anyone know how I might be able to get the BindingExpression (and binding value) for the content of a HyperLinkButton?

Was it helpful?

Solution

have you tried adding the correct binding flags for that field? It sounds like a case of inadaquate binding flags when using reflection. TextBlock has a the Text static field right on TextBlock, where as HyperlinkButton has Content inherited from ContentControl.

Try using the Static & Public & FlattenedHierarchy binding flags:

FieldInfo fi = fe.GetType().GetField("ContentProperty", BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);

adding the FlattenHierarchy reflection binding flag should tell reflection to look up in the class hierarchy to find that public static field.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top