Bindings not applicable to dynamically loaded xaml

I am successfully using XamlReader to download the XamlReader file and create a FrameworkElement to work with.

In xaml, which I download, there are related expressions such as:

 <TextBlock Text="{Binding DataContextTextProperty}" /> 

If I put FrameworkElement, I will return from XamlReader.Load() to the WPF window, binding everything works fine.

However, in this case, I use Laurent Bugnion's excellent article on creating PNG from WPF / XAML . Since the result of XamlReader.Load() written directly to PNG via a VisualBrush , it seems that the necessary WPF mechanics to invoke binding expressions are bypassed.

This makes me think that the actual bindings are not actually called only by calling XamlReader.Load() , or that they do not work because I don’t know what to do with the absence of a visual tree until you add the FrameworkElement to the existing one visual tree or something else.

Is there anything I can do to ensure that these bindings are invoked?

Thank you very much in advance.

+6
source share
1 answer

I FIXED THIS !!

Ah, let me explain ...

I have no idea how I got to this now, but I found a useful article on MSDN regarding Initialization for objects not in the object tree .

In it, I found the following code example:

 Button b = new Button(); b.BeginInit(); b.Background = Brushes.Blue; b.Width = b.Height = 200; b.EndInit(); b.Measure(paperSize); b.Arrange(new Rect(paperSize)); b.UpdateLayout(); 

I looked at the (again excellent) example from Laurent, which I mentioned in the above question, and configured the use of XamlReader as follows:

 var element = (FrameworkElement)XamlReader.Load(xamlInput); element.BeginInit(); element.DataContext = dataContext; ... element.Measure(renderingSize); element.Arrange(renderingRectangle); element.EndInit(); element.UpdateLayout(); 

I added BeginInit() , EndInit() and UpdateLayout() (although due to an exception, I think UpdateLayout() is the key), and now the binding expressions in dynamically loaded xaml work correctly. Hurrah!

+4
source

Source: https://habr.com/ru/post/897823/


All Articles