如何将一个DataTemplate添加到CollectionContainer?
问题描述:
这是我的具体情况。如何将一个DataTemplate添加到CollectionContainer?
的窗口资源的代码:
...
<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>
...
其中我需要显示集合中的部分:
...
<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>
...
的视图模型(假定其被正确地绑定)
...
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>();
...
类CutomObject(可能不需要显示):
...
public class CustomObject
{
public string firstString;
public string secondString;
public CustomObject()
{
...
}
...
}
...
假设ObservableCollection
具有适当的内容。
我的问题是:如何正确显示集合? 这里是标准:
- 在第一行,就会有一个内含文本的TextBlock,上面写着“样品文本”
- 接下来是一个标签“命令”
- 下一个按钮行(多达
ViewModelObservableCollection_String
项)是TextBlocks。其文本应该是ViewModelObservableCollection_String
单个项目的值。 - 下一行(多达
ViewModelObservableCollection_CustomObject
项)是TextBoxes。其文本应为ViewModelObservableCollection_CustomObject
(连接firstString
和secondString
)的单个项目的值。
正如你所看到的,StackPanel的内容是不止一个Collection的合并,具有不同的DataTemplate
。
如果事情不够清楚,请询问澄清。
答
-
使用
DataTrigger
内ItemTemplate
改变使用Control
ControlTemplate
,而比较Type
。为此使用将返回类型的转换器。,或者
使用
ContentControl
为ItemTemplate
。定义
DataTemplate
指定DataType
在其中。ContentControl
将自动为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>
感谢。你能否详细说明一下?我对WPF比较陌生。 – someone
我认为,你的第二个建议更容易。你能提供一个示例代码吗?如果没有,请给我一些参考。 – someone