我尝试使用不同模板的ItemsControl
显示项取决于其viewModel类型。在第一次看,我是认为它可以做到像我们平时在做ContentControl
:根据ViewModel类型为ItemsControl选择DataTemplate
<ItemsControl ItemsSource="{Binding MyViewModelCollection}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type myNameSpace:myViewModel1}">
<myNameSpace:myControl2/>
</DataTemplate>
<DataTemplate DataType="{x:Type myNameSpace:myViewModel2}">
<myNameSpace:myControl2/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
但不幸的是,你不能有两个DataTemplate
在ItemsControl.ItemTemplate
。 我发现了一个小技巧来做到这一点。
我会使用ContentPresenter而不是ContentControl。后者可能会产生功能性后果(例如'Content Focus'默认情况下'Focusable'和'IsTabStop'为'ContentControl',反映在键盘导航上)。前者也更“轻量级”。 – Grx70
两者都没有更好的使用。见另一个答案。 – Clemens