2

I have a XAML file representing the main window of a WPF application. Now I want this window to display content that is specified by another XAML file. This works, but the DataContext is lost in the C# code of my UserControl.

I think the <Frame Source=....> is breaking the logical tree of WPF in some way. I'd like to have the same behavior as if <Frame Source=....> was simply substituted by the Content1.xaml file content, i.e. that the DataContext of the surrounding Window class is inherited to the UserControl.

Is there a simple way to overcome this issue? All solutions that I found seem like overkill.

Pseudocode

MainWindow.xaml

<Window ....>
    <Frame Source="Content1.xaml" />
</Window>

Content1.xaml

<UserControl ....>
  <!-- Content goes here -->
</UserControl>
H.B.
  • 166,899
  • 29
  • 327
  • 400
CrashOverride
  • 21
  • 1
  • 3
  • 1
    Have a look at the response from Joe White here http://stackoverflow.com/questions/3621424/page-datacontext-not-inherited-from-parent-frame – Michael Apr 04 '12 at 08:32
  • @Michael Joe White's solution works for me. I think you can post the link as an answer to this question. – kennyzx Jan 12 '14 at 11:08

1 Answers1

7

Joe White's solution here solves the problem.

Quoting from his answer:

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;
}
Community
  • 1
  • 1
Michael
  • 8,891
  • 3
  • 29
  • 42