Prism DataTemplateSelector With a Single ViewModel

Topics: Prism v4 - Silverlight 4
Nov 18, 2011 at 1: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}"
               <DataTemplate x:Key="DetailType1">
		<DataTemplate x:Key="DetailType2">

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.

Nov 18, 2011 at 6: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}"/>

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

Nov 23, 2011 at 4:30 PM

Hi Damian,

Thanks for your input. It was really useful.