Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

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

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);       
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...