问题
I want to create a WPF TreeView
with two grouping options (radio buttons). So the data will be grouped in two different ways in a 2-level hierarchy, the lowest level being the actual data items, and the groups being just a way to represent the data for easier understanding.
They would also be able to select items by group (checkboxes) but I got that part already figured out, e.g. if I want to represent database objects and want to have them grouped either by schema or by object type (table, view, function, etc.).
I just don't know how I should start on the two grouping modes. Should I entirely restructure my ObservableCollection
whenever the grouping mode changes or is there a more straightforward way?
Also, what if my DataTemplate
for the 2nd level would be slightly different depending on the grouping mode, for example when grouped by object type you need to display the schema on level 2?
Can anyone give me some tips on how to start and which techniques to use?
回答1:
Group your collection by setting GroupDescriptions on its CollectionViewSource. You can do it in code by doing something like this:
CollectionViewSource.GetDefaultView(yourCollection).GroupDescriptions.Add(
new PropertyGroupDescription("PropertyName"));
Or you can do it in XAML by creating a CollectionViewSource explicitly.
<CollectionViewSource
Source="{StaticResource yourCollection}"
xmlns:dat="clr-namespace:System.Windows.Data;assembly=PresentationFramework">
<CollectionViewSource.GroupDescriptions>
<dat:PropertyGroupDescription PropertyName="PropertyName"/>
</CollectionViewSource.GroupDescriptions>
</CollectionViewSource>
If you are using a plain ItemsControl like ListBox then you can just set the GroupStyle property. If you want to use a TreeView, then I think you want to bind to the Groups property on the ICollectionView. You should read Bea Stollnitz's blog entries on grouping:
- How do I display grouped data in a TreeView?
- How can I do custom Grouping?
回答2:
Check this link on HierarchicalDataTemplate
. There are given examples of using it with various types.
来源:https://stackoverflow.com/questions/3263289/grouping-data-in-wpf-treeview