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