我们在用到ItemsControl时,有时会用到分组,如ListBox,ListView,DataGrid。WPF的ItemsControl可以实现分组,是依托于GroupStyle,以ListBox为例,他的分组效果图为:
以下为前台:
1 <ListBox Name="lbMain"> 2 <ListBox.ItemTemplate> 3 <DataTemplate> 4 <StackPanel Orientation="Horizontal"> 5 <TextBlock Text="{Binding FileName}" 6 Width="150" /> 7 <TextBlock Text="{Binding AuthorName}" 8 Width="100" /> 9 <TextBlock Text="{Binding UpTime}" 10 Width="100" /> 11 </StackPanel> 12 </DataTemplate> 13 </ListBox.ItemTemplate> 14 <ListBox.GroupStyle> 15 <GroupStyle> 16 <GroupStyle.ContainerStyle> 17 <Style TargetType="{x:Type GroupItem}"> 18 <Setter Property="Template"> 19 <Setter.Value> 20 <ControlTemplate TargetType="{x:Type GroupItem}"> 21 <Expander IsExpanded="True" 22 ExpandDirection="Down"> 23 <Expander.Header> 24 <StackPanel Orientation="Horizontal"> 25 <TextBlock Text="{Binding Path=Name}" 26 VerticalAlignment="Center" /> 27 <TextBlock Text="{Binding Path=ItemCount, StringFormat=数量:{0}}" 28 VerticalAlignment="Center" 29 Margin="5,0,0,0" /> 30 <Button Content="Sale" 31 Margin="5,0,0,0" /> 32 </StackPanel> 33 </Expander.Header> 34 <ItemsPresenter /> 35 </Expander> 36 </ControlTemplate> 37 </Setter.Value> 38 </Setter> 39 </Style> 40 </GroupStyle.ContainerStyle> 41 </GroupStyle> 42 </ListBox.GroupStyle> 43 </ListBox>
从16行可以看出,GroupStyle定义的是控件内部样式,所以有人尝试在这里绑实体数据属性的话肯定是失败的,注意25行只能是Name,不管分组的属性叫什么名,这都只能是Name,我写了个Button在里面,如果想知道为什么只能是Name,写个Click处理,把Button的DataContext打印出来就什么都知道了。如果想在这里做更多的处理,比如进行一些负责的运算,可以写加转换器。
这里只是弄了一个原始的Expander装载分组控件,需要美化可以另写样式。
以下是后台:
1 public class ModelFile 2 { 3 public string FileName { get; set; } 4 public string AuthorName { get; set; } 5 public string UpTime { get; set; } 6 } 7 8 public partial class MainWindow : Window 9 { 10 public ObservableCollection<ModelFile> CollectionModelFile = new ObservableCollection<ModelFile>(); 11 12 public MainWindow() 13 { 14 InitializeComponent(); 15 16 CollectionModelFile.Add(new ModelFile() { FileName = "WPF进化史", AuthorName = "王鹏", UpTime = "2014-10-10" }); 17 CollectionModelFile.Add(new ModelFile() { FileName = "WPF概论", AuthorName = "大飞", UpTime = "2014-10-10" }); 18 CollectionModelFile.Add(new ModelFile() { FileName = "WPF之美", AuthorName = "小虫", UpTime = "2014-10-11" }); 19 CollectionModelFile.Add(new ModelFile() { FileName = "WPF之道", AuthorName = "青草", UpTime = "2014-11-11" }); 20 CollectionModelFile.Add(new ModelFile() { FileName = "WPF之禅", AuthorName = "得瑟鬼", UpTime = "2014-11-11" }); 21 CollectionModelFile.Add(new ModelFile() { FileName = "WPF入门", AuthorName = "今晚吃什么", UpTime = "2014-11-11" }); 22 CollectionModelFile.Add(new PropertyGroupDescription("UpTime"));
}
31 }
重点是28、29行,有了这两句,ListBox就能准确得分组显示了,其他ItemsControl的分组类同。
至此一个简单的ListBox分组显示就完成了,Demo已放群里,需要的可以下载来看。