2012-01-24 40 views
2

我有一個代表WPF應用程序主窗口的XAML文件。 現在我希望這個窗口顯示由另一個XAML文件指定的內容。 這可行,但DataContext丟失在我的UserControl的C#代碼中。框架導航 - DataContext未繼承

我認爲<Frame Source=....>以某種方式打破了WPF的邏輯樹。 我想要具有相同的行爲,就好像<Frame Source=....>Content1.xaml文件內容簡單地替換,即周圍的Window類的DataContext繼承到UserControl

有沒有簡單的方法來解決這個問題? 所有solutions,我發現似乎是矯枉過正。

MainWindow.xaml

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

Content1.xaml

<UserControl ....> 
    <!-- Content goes here --> 
</UserControl> 
+1

看一看從喬·懷特這裏的響應http://stackoverflow.com/ question/3621424/page-datacontext-not-inherited-from-parent-frame – Michael

+0

@Michael Joe White的解決方案適用於我。我想你可以將鏈接發佈爲這個問題的答案。 – kennyzx

回答

5

喬·懷特的解決方案here解決了這個問題。

從他的回答引用:

在XAML:

<Frame Name="frame" 
     LoadCompleted="frame_LoadCompleted" 
     DataContextChanged="frame_DataContextChanged"/> 

在代碼隱藏:

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

太棒了!謝謝 ! – Jacob

+0

您對參數有問題(反正不會使用它)。 – denver