Search code examples
wpfdatatemplate

WPF DataTemplate ContentPresenter "Binding"


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.


Solution

  • 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.