You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对直接通过XAML添加的ListView项进行分组?

实现方案

该需求完全可以实现,不需要绑定ItemsSource数据源,直接通过XAML声明分组即可,不同平台的写法如下:

WPF 平台实现

你可以先声明ListView的分组集合,再给每个ListViewItem指定所属分组,示例代码如下:

<ListView Name="List">
    <!-- 定义所有分组 -->
    <ListView.Groups>
        <ListViewGroup Header="水果"/>
        <ListViewGroup Header="蔬菜"/>
    </ListView.Groups>

    <!-- 列表项关联对应分组 -->
    <ListViewItem Content="Apple" Group="{Binding ElementName=List, Path=Groups[0]}"/>
    <ListViewItem Content="Orange" Group="{Binding ElementName=List, Path=Groups[0]}"/>
    <ListViewItem Content="Tomato" Group="{Binding ElementName=List, Path=Groups[1]}"/>
    <ListViewItem Content="Potato" Group="{Binding ElementName=List, Path=Groups[1]}"/>

    <!-- 可选:自定义分组头部显示样式 -->
    <ListView.GroupStyle>
        <GroupStyle>
            <GroupStyle.HeaderTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Header}" FontWeight="Bold" Background="LightGray" Padding="4,2"/>
                </DataTemplate>
            </GroupStyle.HeaderTemplate>
        </GroupStyle>
    </ListView.GroupStyle>
</ListView>

UWP/WinUI 平台实现

UWP/WinUI平台支持直接把ListViewItem放在ListViewGroup节点内,写法更直观:

<ListView Name="List">
    <ListViewGroup Header="水果">
        <ListViewItem Content="Apple" />
        <ListViewItem Content="Orange" />
    </ListViewGroup>
    <ListViewGroup Header="蔬菜">
        <ListViewItem Content="Tomato" />
        <ListViewItem Content="Potato" />
    </ListViewGroup>

    <!-- 可选:自定义分组头部显示样式 -->
    <ListView.GroupStyle>
        <GroupStyle>
            <GroupStyle.HeaderTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Header}" FontWeight="Bold" Background="LightGray" Padding="4,2"/>
                </DataTemplate>
            </GroupStyle.HeaderTemplate>
        </GroupStyle>
    </ListView.GroupStyle>
</ListView>

你可以根据自己的实际使用平台选择对应写法,修改GroupStyle即可自定义分组的显示效果,不需要修改现有列表项的核心逻辑。


内容的提问来源于stack exchange,提问作者NovemberMan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 13:57:04