page.DataContext 不是从父框架继承的吗?
我在框架 frame
中有一个页面 page
,其中 frame.DataContext = "foo"
。
(page.Parent as Frame).DataContext
是"foo"
。 okpage.DataContext
的 BindingExpression 为null
(也通过 ClearValue 强制)。 确定page.DataContext
为null
。 但我期望“foo”!
为什么 DataContext 没有被继承?据我了解< /a> 框架沙箱内容。但我找不到任何有关此行为的文档 - 谁能指出我提到此行为的地方?
I have a Page page
in a Frame frame
, with frame.DataContext = "foo"
.
(page.Parent as Frame).DataContext
is"foo"
. ok- BindingExpression for
page.DataContext
isnull
(also forced with ClearValue). ok page.DataContext
isnull
. but I expected "foo"!
Why isn't the DataContext inherited? As far as I understand the Frame sandboxes the content. But I couldn't find any documentation of this behavior - can anyone point me to a place where this is mentioned?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您没有具体询问如何可以实现此功能,只是为什么默认情况下无法实现。但是,如果您确实希望页面继承框架的 DataContext,您可以执行以下操作:
在 XAML 中:
在代码隐藏中:
You didn't specifically ask how you could make this work, only why it doesn't by default. However, if you do want your Pages to inherit the Frame's DataContext, you can do this:
In XAML:
In codebehind:
回答有关此行为的文档的问题:这不是 Microsoft 文档,但我有几本 WPF 书籍都提到了这一点。
“Essential Windows Presentation Foundation”说道:(第 160-161 页)
这就是它要说的全部内容——与财产继承无关。
“Windows Presentation Foundation Unleashed 说(第 95 页):
To answer your question about documentation of this behavior: It's not Microsoft documentation, but I have a couple of WPF books that both mention this.
"Essential Windows Presentation Foundation" says: (pp. 160-161)
That's all it has to say -- nothing about property inheritance.
"Windows Presentation Foundation Unleashed says (p. 95):
对于那些想了解如何使
Frame
级联DataContext
的人来说,为了以 @Joe-White 的答案为基础,我会提到这也可以在 XAML 中执行仅有的。对于 WPF 新手,您可以将此 XAML 放入
App.xaml
文件中,以便它将覆盖应用程序中采用默认样式的所有Frame
控件。这意味着您不必在每次使用新的Frame
时编写特定的后台代码。我使用 VisualStudio 2015 可视化设计器(见下图)创建了上面的大部分 XAML,然后添加了
DataContext="{TemplateBinding DataContext}"
来执行级联。To build upon @Joe-White's answer for those who want to know of ways to make the
Frame
cascade theDataContext
, I'll mention that this can also be performed in XAML only.For those that are new to WPF, you can put this XAML in the
App.xaml
file so that it will override allFrame
controls in your application that pick up the default style. This means you don't have to write specific code-behind each time you use a newFrame
.I used the VisualStudio 2015 Visual Designer (see pic below) to create the bulk of the XAML above and then added the
DataContext="{TemplateBinding DataContext}"
to perform the cascade.