如何将 DataTemplate 添加到 CollectionContainer?

How to add a DataTemplate to CollectionContainer?

这是我的具体情况。

Window资源代码:

...
<Window.Resources>
    <ResourceDictionary>
        <CollectionViewSource x:Key="AdditionalStringData" Source="{Binding ViewModelObservableCollection_String}"/>
        <CollectionViewSource x:Key="AdditionalCustomObjectData" Source="{Binding ViewModelObservableCollection_CustomObject}"/>
        <ResourceDictionary.MergedDictionaries>
            ...
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Window.Resources>
...

我需要显示的部分 Collection:

...
<StackPanel>
    <ItemsControl>
        <ItemsControl.ItemsSource>
            <CompositeCollection>
                <TextBlock Text="{Binding ViewModelTextProperty}"/>
                <Button Command="{Binding ViewModelRelayCommand}">Command</Button>
                <CollectionContainer Collection="{Binding Source={StaticResource AdditionalStringData}}" />
                <CollectionContainer Collection="{Binding Source={StaticResource AdditionalCustomObjectData}}" />
            </CompositeCollection>
        </ItemsControl.ItemsSource>
    </ItemsControl>
</StackPanel>
...

ViewModel(假设绑定正确)

...
private string ViewModelTextProperty  { get; set; } = "Sample Text";
public RelayCommand ViewModelRelayCommand { ... }
private ObservableCollection<string> ViewModelObservableCollection_String { get; set; } = new ObservableCollection<string>();
private ObservableCollection<CustomObject> ViewModelObservableCollection_CustomObject { get; set; } = new ObservableCollection<CustomObject>();
...

Class CutomObject(可能不需要显示):

...
public class CustomObject
{
    public string firstString;
    public string secondString;

    public CustomObject()
    {
        ...
    }
    ...
}
...

假定 ObservableCollection 具有正确的内容。

我的问题是:如何正确显示 collection? 这是标准:

如您所见,StackPanel 的内容是多个 Collection 与不同 DataTemplate.

的合并

如有不明白的地方请追问

  1. ItemTemplate中使用DataTrigger来改变使用的ControlControlTemplate,同时比较Type。为此使用一个转换器,该转换器将 return 类型。

    或者,

  2. ContentControl用作ItemTemplate

  3. 定义 DataTemplate 并在其中指定 DataTypeContentControl 会自动为其 ContentTemplate 选择合适的 DataTemplate

第二种方法(推荐)

<Window.Resources>
    <ResourceDictionary>            
        ...
        <DataTemplate DataType="{x:Type sys:String}">
            <TextBlock Background="ForestGreen" Text="{Binding .}"/>
        </DataTemplate>

        <DataTemplate DataType="{x:Type local:CustomObject}">
            <StackPanel Orientation="Horizontal">
                <TextBlock Background="Red" Text="{Binding firstString}"/>
                <TextBlock Background="Red" Text="{Binding secondString}"/>
            </StackPanel>
        </DataTemplate>
    </ResourceDictionary>
</Window.Resources>
<ItemsControl>
... 
 <ItemsControl.ItemTemplate>
    <DataTemplate>
        <ContentControl Content="{Binding .}"/>
    </DataTemplate>
 </ItemsControl.ItemTemplate>
 ...
</ItemsControl>