page.DataContext not inherited from parent Frame?

Marcel Jackwerth picture Marcel Jackwerth · Sep 1, 2010 · Viewed 9k times · Source

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 is null (also forced with ClearValue). ok
  • page.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?

Answer

Joe White picture Joe White · Sep 4, 2010

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;
}