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

我与影子孤独终老i 提交于 2019-12-13 22:13:37

问题


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.



来源:https://stackoverflow.com/questions/39203220/why-does-this-datacontext-window-show-data-from-viewmodel-and-framecontent-dat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!