I have a Page page
in a Frame frame
, with frame.DataContext = "foo"
.
(page.Parent as Frame).DataContext
is "foo"
. okpage.DataContext
is null
(also forced with ClearValue). okpage.DataContext
is null
. 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?
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:
<Frame Name="frame"
LoadCompleted="frame_LoadCompleted"
DataContextChanged="frame_DataContextChanged"/>
In codebehind:
private void frame_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
UpdateFrameDataContext(sender, e);
}
private void frame_LoadCompleted(object sender, NavigationEventArgs e)
{
UpdateFrameDataContext(sender, e);
}
private void UpdateFrameDataContext(object sender, NavigationEventArgs e)
{
var content = frame.Content as FrameworkElement;
if (content == null)
return;
content.DataContext = frame.DataContext;
}