绑定不适用于动态加载的 xaml
我正在使用 XamlReader
成功加载 xaml 文件并创建要使用的 FrameworkElement
。
我正在加载的 xaml 中包含绑定表达式,例如:
<TextBlock Text="{Binding DataContextTextProperty}" />
如果我将从 XamlReader.Load()
返回的 FrameworkElement 放入 WPF 窗口中,则绑定一切正常。
但是,在这种情况下,我使用 Laurent Bugnion 关于从 WPF/XAML 创建 PNG 的优秀文章。由于 XamlReader.Load() 的结果是通过 VisualBrush 直接写入 PNG,因此似乎绕过了 WPF 调用绑定表达式的必要机制。
这让我相信实际的绑定并不是真的通过调用 XamlReader.Load() 来调用,或者它们因为我不知道的事情而无法工作在将 FrameworkElement
添加到现有可视化树或其他内容之前,不会有可视化树。
我可以做些什么来确保调用这些绑定吗?
非常感谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我修好了!
咳咳,请允许我解释一下...
我现在不知道如何做到这一点,但我在 MSDN 上找到了一篇关于 初始化不在对象树中的对象。
在其中,我找到了以下代码示例:
我查看了我在上面的问题中提到的 Laurent 的(再次出色的)示例,并自定义了
XamlReader
的使用,如下所示:我添加了
BeginInit()
、EndInit()
和UpdateLayout()
(尽管通过排除过程,我相信UpdateLayout()
是键),现在是绑定表达式我的动态加载的 xaml 工作正常。欢呼!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!