您可以在您的收藏上创建一个收藏视图,并告诉它按您的Group
属性分组。然后,您可以GroupStyle
在 yourListBox
上定义一个来定义分组的可视化方式。
这是一个简单的示例(不遵循最佳实践或 MVVM 或任何东西,但用于说明您的场景的集合视图):
MainWindow.xaml.cs:
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;
using System.Windows.Data;
namespace SO11343251
{
public partial class MainWindow : Window
{
private readonly ICollection<ViewLookupItem> items;
private readonly ICollectionView itemsView;
public MainWindow()
{
InitializeComponent();
this.items = new List<ViewLookupItem>();
this.items.Add(new ViewLookupItem("Amenities", "No Group"));
this.items.Add(new ViewLookupItem("Indoor", "Area"));
this.items.Add(new ViewLookupItem("Outdoor", "Area"));
this.itemsView = new ListCollectionView((IList)this.items);
this.itemsView.GroupDescriptions.Add(new PropertyGroupDescription("Group"));
this.DataContext = this;
}
public ICollection<ViewLookupItem> Items
{
get { return this.items; }
}
public ICollectionView ItemsView
{
get { return this.itemsView; }
}
}
public class ViewLookupItem
{
private readonly string name;
private readonly string group;
public ViewLookupItem(string name, string group)
{
this.name = name;
this.group = group;
}
public string Name
{
get { return this.name; }
}
public string Group
{
get { return this.group; }
}
}
}
MainWindow.xaml:
<Window x:Class="SO11343251.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<ListBox ItemsSource="{Binding ItemsView}">
<ListBox.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<TextBlock x:Name="textBlock" FontWeight="Bold" Text="{Binding Name}"/>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Name}" Value="No Group">
<Setter TargetName="textBlock" Property="Visibility" Value="Collapsed"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</ListBox.GroupStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Window>
结果: