在WPF ListView中对项目进行分组,可以使用CollectionViewSource
和PropertyGroupDescription
来实现。下面是一个简单的示例:
<CollectionViewSource x:Key="groupedItems" Source="{Binding Items}">
<CollectionViewSource.GroupDescriptions>
<PropertyGroupDescription PropertyName="Category"/>
</CollectionViewSource.GroupDescriptions>
</CollectionViewSource>
</Window.Resources><ListView ItemsSource="{Binding Source={StaticResource groupedItems}}">
<ListView.View>
<GridView>
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/>
<GridViewColumn Header="Category" DisplayMemberBinding="{Binding Category}"/>
</GridView>
</ListView.View>
<ListView.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<TextBlock FontWeight="Bold" Text="{Binding Name}"/>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</ListView.GroupStyle>
</ListView>
public class Item
{
public string Name { get; set; }
public string Category { get; set; }
}
public class MainViewModel
{
public ObservableCollection<Item> Items { get; set; }
public MainViewModel()
{
Items = new ObservableCollection<Item>
{
new Item { Name = "Item 1", Category = "Category A" },
new Item { Name = "Item 2", Category = "Category B" },
new Item { Name = "Item 3", Category = "Category A" },
new Item { Name = "Item 4", Category = "Category C" },
new Item { Name = "Item 5", Category = "Category B" },
};
}
}
public MainWindow()
{
InitializeComponent();
DataContext = new MainViewModel();
}
这样就可以在ListView中对项目进行分组了。在这个示例中,我们使用了CollectionViewSource
和PropertyGroupDescription
来对数据进行分组,并在ListView中显示分组后的数据。你可以根据自己的需求进行调整。
领取专属 10元无门槛券
手把手带您无忧上云