我有一个ListView,它包含两种类型的对象,单个和多个。 单个是普通的TextBlock,而倍数是带有项目的ComboBox。
我正在尝试将ComboBox中的项目分组但没有成功。可能吗?或者我应该采取不同的方法?
我想要实现的目标:
[ComboBox v]
[Header ]
[ Item]
[ Item]
[Header ]
[ Item]
答案 0 :(得分:57)
有可能。使用带有GroupDescription的ListCollectionView作为ItemsSource,只需向ComboBox提供GroupStyle。见下面的示例:
XAML:
<Window x:Class="StackOverflow.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:StackOverflow"
xmlns:uc="clr-namespace:StackOverflow.UserControls"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<ComboBox x:Name="comboBox">
<ComboBox.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</ComboBox.GroupStyle>
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</StackPanel>
</Window>
代码隐藏:
namespace StackOverflow
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
//this.comboBox.DataContext = this;
List<Item> items = new List<Item>();
items.Add(new Item() { Name = "Item1", Category = "A" });
items.Add(new Item() { Name = "Item2", Category = "A" });
items.Add(new Item() { Name = "Item3", Category = "A" });
items.Add(new Item() { Name = "Item4", Category = "B" });
items.Add(new Item() { Name = "Item5", Category = "B" });
ListCollectionView lcv = new ListCollectionView(items);
lcv.GroupDescriptions.Add(new PropertyGroupDescription("Category"));
this.comboBox.ItemsSource = lcv;
}
}
public class Item
{
public string Name { get; set; }
public string Category { get; set; }
}
}