Prism DataTemplateSelector With a Single ViewModel

Topics: Prism v4 - Silverlight 4
Nov 18, 2011 at 12:45 PM

I have a requirement where in I am having a Silverlight Page consisting of Master-Detail View. The Detail Section gets changed dynamically based on a Combo box selection in Master View. I am now using Prism DataTemplateSelector to dynamically load the detail view based on the Entity Type of Detail.

<prism:DataTemplateSelector Content="{Binding}"
                                     HorizontalContentAlignment="Stretch"
                                     IsTabStop="False">
               <prism:DataTemplateSelector.Resources>
               <DataTemplate x:Key="DetailType1">
                  <views:DetailOneView>
                </DataTemplate>
		<DataTemplate x:Key="DetailType2">
                  <views:DetailTwoView>
                </DataTemplate>
  </prism:DataTemplateSelector.Resources>
      </prism:DataTemplateSelector>

In my application, I have only one ViewModel (MainViewModel) which will serve as the DataContext for the Master View and all the Detail Views. So when i choose the
Detail View based on the above shown code, the DetailType1 & DetailType2 classes becomes the DataContext for the DetailOneView and DetailTwoViews respectively, even
though I set the DataContext of DetailOneView and DetailTwoView to MainViewModel in the Xaml.cs of both views.

How do i explicitly make the MainViewModel as the DataContext for DetailOneView and DetailTwoView while using DataTemplateSelector. 
Any help is appreciated.

Thanks
Syam
Developer
Nov 18, 2011 at 5:56 PM

Hi Syam,

Based on my understanding, when you use a DataTemplateSelector the data context of the view that you want to show will be the object "selected" in the DataTemplateSelector.

As a possible approach, you could define the data context of your MasterView (that is, the MainViewModel) as a resource of the MasterView (for example, in the code behind) and then use bindings to set the DataContext property of your DetailView as that resource:

<DataTemplate x:Key="DetailType1">
         <views:DetailOneView DataContext="{StaticResource MainViewModelResource}"/>
</DataTemplate>

Note that usually, DataTemplateSelector is used to select which data template is going to be applied to an element based on that element's type. If you wish to show a view that uses the same view model that your MasterView you might find other approaches (like view injection) more useful.

I hope you find this useful,

Damian Cherubini
http://blogs.southworks.net/dcherubini

Nov 23, 2011 at 3:30 PM

Hi Damian,

Thanks for your input. It was really useful.

Thanks

Syam