I'm using XamlReader
successfully to load a xaml file and create a FrameworkElement
to work with.
The xaml I'm loading has binding expressions in it such as:
<TextBlock Text="{Binding DataContextTextProperty}" />
If I place the FrameworkElement I get back from XamlReader.Load()
into a WPF window, the binding all works fine.
However, in this case I'm using Laurent Bugnion's excellent article on creating PNGs from WPF/XAML. Since the result of XamlReader.Load()
is written directly to a PNG via a VisualBrush
, it seems the necessary mechanics of WPF to invoke binding expressions are bypassed.
This leads me to believe that the actual bindings aren't really being invoked just by calling XamlReader.Load()
, or that they're not working because of something I don't know about to do with there not being a visual tree until you add the FrameworkElement
to an existing visual tree or something.
Is there something I can do to ensure these bindings are invoked?
Many thanks in advance.
I FIXED IT!!
Ahem, allow me to explain...
I have no idea how I got to it now, but I found a helpful-sounding article on MSDN regarding Initialization for Objects Not in an Object Tree.
In it I found the following code example:
I looked at the (again, excellent) example from Laurent that I mentioned in the question above, and customised the use of
XamlReader
as follows:I added the
BeginInit()
,EndInit()
andUpdateLayout()
(though by process of elimination I believeUpdateLayout()
is the key) and now the binding expressions in my dynamically-loaded xaml are working correctly. Hurrah!