views:

36

answers:

1

I had been setting the DataContext for UserControls like so:

<uc:DepartmentListingView DataContext="{Binding ., Mode=TwoWay}" />

Based on a sample project by Josh Smith I am trying to accomplish the same thing with a DataTemplate and DataType:

<!-- Template applies a DepartmentListingView to an instance of the DepartmentSelectionViewModel class. -->
<DataTemplate DataType="{x:Type model:DepartmentSelectionViewModel}">
    <uc:DepartmentListingView />
</DataTemplate>

This works well, but of course there is a problem; I think it might arise from trying to set more than one view (UserControl) to the same view model(?). In the code below I am now associating the same viewModel from above with a different view in the same window.

<DataTemplate DataType="{x:Type model:DepartmentSelectionViewModel}">
    <uc:ListSubjectHeaderView />
</DataTemplate>

The first view is wired the same as it was when I set the DataContext explicitly but the last view gets no binding, although no obvious DataBinding error in the console either.

So, would resusing the DataType / DataTemplate trick this way be the problem?

Thanks,
Berryl

A: 

Ideally you will have a one to one relationship between a view and viewmodel.

To get what you want perhaps subclass your viewmodel with nothing extra and have that subclassed viewmodel as the datatype in the datatemplate.

That way just creating the correct viewmodel will drive the correct datatemplate and therefore usercontrol

aqwert
Thanks for the reply, but that seems pretty hacky even if it worked. I asked a related question from a different perspective [here](http://stackoverflow.com/questions/3205338/usercontrol-as-content-for-headeredcontentcontrol-headertemplate) where I am trying to inline the template. Any other ideas?
Berryl