你看过 ItemTemplateSelector 属性吗?
例如,创建一个内容选择器类:
public class myContentSelector : DataTemplateSelector
{
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
if (item != null)
{
VMBase vm = item as VMBase;
switch (vm.Type)
{
case myType.General:
return Application.Current.Resources["GeneralSettings"] as DataTemplate;
default:
return Application.Current.Resources["AdvancedSettings"] as DataTemplate;
}
}
return null;
}
}
为它创建一个静态资源:
<local:myContentSelector x:Key="contentSelector" />
并在 ItemsControl 中设置:
<ItemsControl ItemsSource="{Binding mySource}" ItemTemplateSelector="{StaticResource contentSelector}" />
并将您的数据模板设置为名称:
<DataTemplate x:Key="GeneralSettings" DataType="{x:Type vm:VMBase}">
<View:GeneralSettingsView/>
</DataTemplate>
<DataTemplate x:Key="AdvancedSettings" DataType="{x:Type vm:VMBase}">
<View:AdvancedSettingsView/>
</DataTemplate>
类似的东西?