In the MainWindow.xaml, I set:
<Window.DataContext>
<vm:MainViewModel/>
</Window.DataContext>
In the App.xaml file, I added the following:
<Application.Resources>
<DataTemplate DataType="vm:MainViewModel">
<v:MainView/>
</DataTemplate>
</Application.Resources>
I was hoping the MainWindow will automatically load and show the MainView with its DataContext property set to the windows’s one (which was set to MainViewModel at design-time as above), but it won’t work – the MainWindow doesn’t use the DataTemplate set in App.xaml.
Any better ideas for this scenario?
You should make a minor changes –
First, in your window. Try this:
This creates a single content item within your Window. DataTemplates work by mapping content to a new View – in this case, since the Content here is the
MainViewModel, it will automatically create and instantiate a newMainViewfor you. Setting theDataContextwill not triggerDataTemplates, since you’re never making the ViewModel “content” of an object.You can shorten this by just setting the Window’s Content directly, if you prefer:
Or, even, binding the Content to the
DataContext(though this only makes sense if you need theDataContextset for some other purpose):