wpf 组合框中的项目分组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3585017/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Grouping items in a ComboBox
提问by debe
I have a ListView that contains two types of objects, single and multiple. The single is a ordinary TextBlock while the multiple is a ComboBox with items.
我有一个 ListView,它包含两种类型的对象,单个对象和多个对象。单个是普通的 TextBlock,而多个是带有项目的 ComboBox。
I'm trying to group the items in the ComboBox without success. Is it possible? Or should I go for a different approach?
我试图对 ComboBox 中的项目进行分组,但没有成功。是否可以?或者我应该采取不同的方法?
What I'm trying to achieve:
我正在努力实现的目标:
[ComboBox v]
[Header ]
[ Item]
[ Item]
[Header ]
[ Item]
回答by ASanch
It is possible. Use a ListCollectionViewwith a GroupDescription as the ItemsSource and just provide a GroupStyle to your ComboBox. See sample below:
有可能的。使用带有 GroupDescription的ListCollectionView作为 ItemsSource,并为您的 ComboBox 提供 GroupStyle。请参阅下面的示例:
XAML:
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>
Code-behind:
代码隐藏:
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; }
}
}