我正在尝试对基于以下模型的集合进行分组:
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; }
}
我的个人收藏,
public ObservableCollection<Person> PersonList;
集合中有三个 Person 对象,其中两个角色相同。
我希望按照 RoleName 将所有的人分组。以下是我的 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>
然而,渲染后的UI没有在列表框中显示分组的RoleName。另外,我想将分组水平显示,其中分组水平出现,而分组项垂直出现。提前感谢任何帮助。
以下是输出内容:
![enter image description here](https://istack.dev59.com/nD575.webp)