(1)改写了Data类,增加了Level1、Level2两个属性,可以让数据先根据Level1 Grouping,然后在根据Level2 Grouping。
(2)对GroupItem 的 ControlTemplate 增加了Marging和Padding,好让UI看上去有层次感。除此之外,我没有做任何改动!
数据结构:
class Data { public string Level1 { get; set; } public string Level2 { get; set; } public string Value { get { return String.Format("Level {0}-{1}", Level1, Level2); } } }
XAML:
<Window x:Class="WpfApplication2.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfApplication2" Title="MainWindow" SizeToContent="WidthAndHeight"> <Window.Resources> <DataTemplate DataType="{x:Type local:Data}"> <TextBlock Text="{Binding Value}"/> </DataTemplate> </Window.Resources> <StackPanel Margin="5"> <ListBox ItemsSource="{StaticResource data}"> <ListBox.GroupStyle> <GroupStyle> <GroupStyle.ContainerStyle> <Style TargetType="GroupItem"> <Setter Property="Template"> <Setter.Value> <ControlTemplate> <Expander Header="{Binding Name}" Padding="3"> <ItemsPresenter Margin="5,0,0,0" /> </Expander> </ControlTemplate> </Setter.Value> </Setter> </Style> </GroupStyle.ContainerStyle> </GroupStyle> </ListBox.GroupStyle> </ListBox> </StackPanel> </Window>
代码:
/// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { ObservableCollection<Data> data = new ObservableCollection<Data>(); data.Add(new Data() { Level1 = "1-1", Level2 = "1" }); data.Add(new Data() { Level1 = "1-1", Level2 = "1" }); data.Add(new Data() { Level1 = "1-1", Level2 = "2" }); data.Add(new Data() { Level1 = "1-1", Level2 = "2" }); data.Add(new Data() { Level1 = "1-2", Level2 = "1" }); data.Add(new Data() { Level1 = "1-2", Level2 = "1" }); data.Add(new Data() { Level1 = "1-2", Level2 = "2" }); data.Add(new Data() { Level1 = "1-2", Level2 = "2" }); this.Resources.Add("data", data); InitializeComponent(); ICollectionView vw = CollectionViewSource.GetDefaultView(data); vw.GroupDescriptions.Add(new PropertyGroupDescription("Level1")); vw.GroupDescriptions.Add(new PropertyGroupDescription("Level2")); } } class ControlStyleSelector : StyleSelector { public override Style SelectStyle(object item, DependencyObject container) { return base.SelectStyle(item, container); } }
运行截图:
可以看到,级联Grouping是很容易实现的,假如你要对不同的Grouping设置不同的Style也是可以的,你可以在ContainerStyleSelector增加代码逻辑,为不同的Grouping返回不同的Style。