views:

50

answers:

2

We are loading some xaml for an Element at runtime (XamlReader.Load) for some preview purposes. Need less to say, the properties/bindings are not know as they can vary across elements/controls we are loading.

As the run time view model context is not available when we load the control for preview - after loading the Element, the idea is to grab the binding information, create a type with those propertes at run time, to assign the same as the data context of the loaded control.

We'll be using AssemblyBuilder/ModuleBuilder/TypeBuilder to build a type at run time. Having said that, we need to walk the visual tree to identify the bindings involved, to create a list of binding paths.

Obviously, one way is to use regex to parse the xaml directly and build this list.. Just want to know a way exist so that I can grab the bindings and related paths from the visual tree itself?

Thanks

A: 

Why not just walk the Silverlight Visual Tree and for each element call GetBindingExpression() for all of it's DPs?

JustinAngel
One dev's "simple" is another dev's "yikes!".
AnthonyWJones
Perfect, thanks
amazedsaint
A: 

You can't easily the enumerate the bindings themselves from the visual tree. The primary showstopper is that the FrameworkElement does not provide a means to enumerate bindings that have been applied using the SetBinding method.

In order to discover the bindings set on a FrameworkElement you would need to discover the set of possible DependencyProperties that may or may not have been set then attempt to retrieve each with GetBindingExpression. To discover the set of DependencyProperties would require some reflection code over the actual type of the FrameworkElement.

A more likely alternative would be to load the XAML into an XDocument, you could then use some LINQ to discover all Attributes that start with "{Binding". But yes it would then be a case of RegEx to parse the attribute value (unless you want to do something really mad that I won't even mention).

AnthonyWJones