ListBox分组问题

9

我正在尝试对基于以下模型的集合进行分组:

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

你想要很多... ;) 发布你的示例,以便我们可以处理它。 - dev hedgehog
其实,我只是在试图弄清楚为什么RoleName没有显示出来。水平分组只是次要问题。 - Lucifer
只需发布代码。我不想通过所有模板和测试数据来完成工作。你已经有它们了。 - dev hedgehog
1个回答

19

因为您已经在CollectionViewSource中提供了GroupDescriptions,所以groupStyle只会从那里挑选属性名。

您需要做的就是将其绑定到CollectionViewGroup类的Name属性,以访问应用分组的属性值。在群组样式中,绑定是针对CollectionViewGroup类而不是Model类进行的。

因此,您需要这样做:

<TextBlock Text="{Binding Name}" FontWeight="Bold"
           Background="ForestGreen" Margin="0,5,0,0"/>

而对于水平对齐组,您可以将Group的ItemsPanelTemplate设置为具有Orientation设置为HorizontalVirtualizingStackPanel,这样可以使您的组水平对齐。

<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>

3
谢谢,Rohit。你的解释让我很容易理解了。 - Lucifer
因为它解决了一个无关的问题,所以我投了赞成票。哈哈,谢谢 ;) - user1618054

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接