Why does this.datacontext (Window) show data from

2019-09-21 02:39发布

问题:

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

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.

Below my code:

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

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

回答1:

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).

Therefore your line of code

this.FrameContent.DataContext = new ViewModelEditor1();

is necessary for making you application work.