Bindings not applied to dynamically-loaded xaml

戏子无情 提交于 2019-12-06 01:44:43

问题


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.


回答1:


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:

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 that I mentioned in the question above, and customised 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 the BeginInit(), EndInit() and UpdateLayout() (though by process of elimination I believe UpdateLayout() is the key) and now the binding expressions in my dynamically-loaded xaml are working correctly. Hurrah!



来源:https://stackoverflow.com/questions/7515360/bindings-not-applied-to-dynamically-loaded-xaml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!