DataTemplate DataType usage WPF

余生颓废 提交于 2019-12-12 01:18:27

问题


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:


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



来源:https://stackoverflow.com/questions/3200477/datatemplate-datatype-usage-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!