【问题标题】:Why does this.datacontext (Window) show data from viewModel and FrameContent.datacontext (page) does not?为什么 this.datacontext (Window) 显示来自 viewModel 的数据而 FrameContent.datacontext (page) 不显示?
【发布时间】:2016-08-29 09:48:02
【问题描述】:

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

目前,我将数据从页面视图加载到窗口。 我不想直接将其加载到窗口的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);       
}

【问题讨论】:

    标签: c# wpf mvvm window datacontext


    【解决方案1】:

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

    因此你的代码行

    this.FrameContent.DataContext = new ViewModelEditor1();
    

    必要让您的应用程序工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-22
      相关资源
      最近更新 更多