为什么this.datacontext(窗口)显示viewModel中的数据而FrameContent.datacontext(页面)不显示数据? [英] Why does this.datacontext (Window) show data from viewModel and FrameContent.datacontext (page) does not?

查看:462
本文介绍了为什么this.datacontext(窗口)显示viewModel中的数据而FrameContent.datacontext(页面)不显示数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么this.datacontext(窗口)显示viewModel的数据而FrameContent.datacontext(页面)不显示?

Why does this.datacontext (Window) show data from viewModel and FrameContent.datacontext (page) does not?

当前,我从页面视图加载数据到窗户。
不是直接将其加载到窗口的dataContext中,而是要将其加载到显示数据的框架的dataContext中。

Currently, I load the data from a page's view to the window. Instead of loading it directly to the dataContext of the window, I want to load it in the dataContext of the frame where the data is showed.

代码:

ViewConfiguration.xaml:

ViewConfiguration.xaml:

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

ViewConfiguration.xaml.cs:

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

我怀疑这样的事情会起作用,但不会起作用。

I suspected that something like this would work, but does not.

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


推荐答案

Adam Nathan 在他的书 WPF释放(请看第4章,介绍WPF控件), Frame 控件用于 隔离 的内容来自用户界面的其余部分,因此由于这个原因,它不会继承其父级的属性(包括 DataContext )。

As Adam Nathan states in his book WPF Unleashed (take a look to Chapter 4, "Introducing WPF's Controls"), Frame control is used for isolating its content from the rest of your user interface, so for this reason it does not inherit its parent's properties (DataContext included).

因此您的代码行

this.FrameContent.DataContext = new ViewModelEditor1();

对于使您的应用程序正常运行是必需的。

is necessary for making you application work.

这篇关于为什么this.datacontext(窗口)显示viewModel中的数据而FrameContent.datacontext(页面)不显示数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆