为什么this.datacontext(Window)显示来自viewModel和FrameContent.datacontext(页面)的数据不?

时间:2016-08-29 09:48:03

标签: c# wpf mvvm window datacontext

为什么this.datacontext(Window)显示来自viewModel和FrameContent.datacontext(页面)的数据不是?

目前,我将页面视图中的数据加载到窗口中。 我不想将它直接加载到窗口的dataContext中,而是将其加载到显示数据的帧的dataContext中。

在我的代码下面:

ViewConfiguration.xaml:

<Frame x:Name="FrameContent" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" NavigationUIVisibility="Hidden" BorderThickness="0"/>

ViewConfiguration.xaml.cs:

namespace Modules.Configuration
{
    public partial class ViewConfiguration : Window
    {
        public ViewConfiguration()
        {
           InitializeComponent();
           ViewModelConfiguration ViewModelConfiguration = new ViewModelConfiguration();

        }   

        private void PageEditor1_Click(object sender, RoutedEventArgs e)
        {
            this.DataContext = new ViewModelEditor1();
            FrameContent.Source = new Uri("/Modules/Editor1/View/ViewEditor1.xaml", UriKind.Relative);

        }

        private void PageEditor2_Click(object sender, RoutedEventArgs e)
        {
            this.DataContext    = new ViewModelEditor2();
            FrameContent.Source = new Uri("/Modules/Editor2/View/ViewEditor2.xaml", UriKind.Relative);
        }
    }
}

我怀疑这样的事情会奏效,但事实并非如此。

private void PageEditor1_Click(object sender, RoutedEventArgs e)
{
    // this.DataContext = new ViewModelEditor1();           // loading in datacontext of window
    this.FrameContent.DataContext = new ViewModelEditor1(); // loading in datacontext of frame
    FrameContent.Source = new Uri("/Modules/Editor1/View/ViewEditor1.xaml", UriKind.Relative);       
}

1 个答案:

答案 0 :(得分:1)

正如Adam Nathan在他的书WPF Unleashed中所述(请参阅第4章“WPF控件简介”),Frame控件用于 隔离< / em> 来自其他用户界面的内容,因此它不会继承其父级属性(包括DataContext)。

因此你的代码行

this.FrameContent.DataContext = new ViewModelEditor1();

必要的,用于使您的应用程序正常工作。