Can someone explain me how the code I am using here can work?

<Window.Resources>
    <DataTemplate DataType="{x:Type VM:PBRKEntryViewModel}">
        <V:Overview  />
    </DataTemplate>
    <DataTemplate DataType="{x:Type VM:LoginViewModel}">
        <V:LoginView />
    </DataTemplate>
</Window.Resources>
<Grid>
    <ContentPresenter Content="{Binding CurrentView}"/>
</Grid>       

My current problems in Details are:

  • Why can the ContentPresenter present the correct UserControl without Reference to the different DataTemplates? I can see, that ContentPresenter content is bound to my ViewModels CurrentViewProperty but my DataTemplates not?
  • Another great feature is that the UserControls using the correct ViewModels without a declaration. (Or without a declaration I can see)

I have found this description http://msdn.microsoft.com/en-us/library/System.Windows.Controls.ContentPresenter(v=vs.110).aspx but the remarks section has no answer to this questions. (Or I couldn´t see them...)

Again and just for clarity everything is working perfect, but I do not understand why, so this is just a question to understand the Selection of the template and the Binding.

有帮助吗?

解决方案

DateTemplates that specify a DataType property are automatically applied to any instance of that type in the view. It's just a way to tell WPF "every time you need to display this type, use this template"

Your ContentPresenter has its Content bound to some object. If that object type has a matching template, then WPF will use it.

其他提示

Under the remarks section of the link you posted it's clear enough with this statement:

If there is a DataTemplate associated with the type of Content, the ContentPresenter applies that DataTemplate to the Content property and the resulting UIElement and its child elements, if any, are displayed.

Also, if you want to know how dataTemplates are picked automatically, you can read about it here - Data Templating Overview.

Quote from the link:

The DataTemplate class has a DataType property that is very similar to the TargetType property of the Style class. DataTemplate gets applied automatically to all objects associated with underlying type.

This is something similar to Styles. If you doesn't specify any x:Key on your Style it will be applied automatically to all child elements falling under the root element where resource is defined.

As soon as you set x:Key on Style, it is no more a default style and will be applied only to the elements explicitly setting style to this resource.

Same holds true for DataTemplate as well. When you specify DataType only, it becomes default template to represent underlying data type. Explicitly specifying x:Key will break this feature.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top