Bindings not applied to dynamically-loaded xaml

不羁的心 提交于 2019-12-04 05:19:40

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!

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