I am trying to Group my collection which is based on my following model:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Role PersonRole { get; set; }
}
public class Role
{
public int Id { get; set; }
public string RoleName { get; set; }
}
My PersonCollection,
public ObservableCollection<Person> PersonList;
The collection is populated with three Person object, two with identical roles.
I want to group all my persons as per their RoleName. I have the following XAML:
<Grid.Resources>
<CollectionViewSource x:Key="cvs" Source="{Binding PersonList}">
<CollectionViewSource.GroupDescriptions>
<PropertyGroupDescription PropertyName="PersonRole.RoleName"/>
</CollectionViewSource.GroupDescriptions>
</CollectionViewSource>
</Grid.Resources>
<ListBox ItemsSource="{Binding Source={StaticResource cvs}}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding FirstName}"/>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding PersonRole.RoleName}" FontWeight="Bold" Background="ForestGreen" Margin="0,5,0,0"/>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</ListBox.GroupStyle>
</ListBox>
However the rendered UI is not displaying the grouped RoleName in the list box. Also I would like to show the grouping horizontally where the groups appear horizontally while the grouped items appear vertically. Appreciate any help in advance.
Here's the output I am seeing:
Since you have already provided GroupDescriptons
at your CollectionViewSource, groupStyle will pick the property name from there only.
All you need is to bind with Name
property of CollectionViewGroup
class to access the value of the property on which grouping is applied. In group style, binding is against CollectionViewGroup class and not against your Model class.
So, this is how you will do it:
<TextBlock Text="{Binding Name}" FontWeight="Bold"
Background="ForestGreen" Margin="0,5,0,0"/>
And regarding to align groups horizontally, you can set ItemsPanelTemplate
of Group to be VirtualizingStackPanel
with Orientation
set to Horizontal
which makes your groups to be aligned horizontally.
<ListBox.GroupStyle>
<GroupStyle>
<GroupStyle.Panel>
<ItemsPanelTemplate>
<VirtualizingStackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</GroupStyle.Panel>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" FontWeight="Bold"
Background="ForestGreen" Margin="0,5,0,0"/>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</ListBox.GroupStyle>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With