DataTemplate DataType usage WPF

2019-09-14 19:47发布

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

1条回答
啃猪蹄的小仙女
2楼-- · 2019-09-14 20:17

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

查看更多
登录 后发表回答