WPF implicit DataTemplate declared in App.xaml won't take effect
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
.
An开发者_开发知识库y better ideas for this scenario?
You should make a minor changes -
First, in your window. Try this:
<Window>
<!-- setup window... -->
<ContentPresenter>
<ContentPresenter.Content>
<vm:MainViewModel/>
</ContentPresenter.Content>
</ContentPresenter>
</Window>
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 new MainView
for you. Setting the DataContext
will not trigger DataTemplates
, 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:
<Window>
<Window.Content>
<vm:MainViewModel/>
</Window.Content>
</Window>
Or, even, binding the Content to the DataContext
(though this only makes sense if you need the DataContext
set for some other purpose):
<Window Content="{Binding}">
<Window.DataContext>
<vm:MainViewModel/>
</Window.DataContext>
</Window>
I think you need
<DataTemplate DataType="{x:Type vm:MainViewModel}">
EDIT:
I really don't think I'm wrong, the code
<Window.DataContext>
<WpfApplication1:ViewModel />
</Window.DataContext>
<Window.Resources>
<DataTemplate DataType="{x:Type WpfApplication1:ViewModel}">
<TextBlock>Custom template</TextBlock>
</DataTemplate>
</Window.Resources>
<ContentPresenter Content="{Binding}" />
shows “Custom template”. If I remove the x:Type
, what's shown instead is “WpfApplication1.ViewModel”, which is the result of calling ToString()
on the view model object. This is used in the absence of a DataTemplate
.
精彩评论