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

WPF嵌套Expander分组产品异常:无分类名及产品显示

问题修复方案

1. 修正CollectionViewSource的数据源绑定

你的DataContext是BBB对象,其中AAA属性才是ObservableCollection<Product>,但当前代码里的Source绑定写错了,需改为绑定AAA:

<CollectionViewSource x:Key="GroupedProductsSource" 
                      Source="{Binding AAA}">
    <CollectionViewSource.GroupDescriptions>
        <PropertyGroupDescription PropertyName="CategoryName" />
    </CollectionViewSource.GroupDescriptions>
</CollectionViewSource>

2. 为父分类Expander绑定Header

分组后,外层ItemsControl的每个数据项是CollectionViewGroup类型,它的Name属性对应分组的CategoryName,给父Expander绑定这个属性才能显示分类名称:

<Expander x:Name="CategoryExpander" Header="{Binding Name}">

3. 确保产品Expander的样式正确绑定数据

内层ProductExpander使用的ProductExpanderStyle,需要在样式里正确绑定Product的Name属性,比如设置Expander的Header:

<Style x:Key="ProductExpanderStyle" TargetType="Expander">
    <Setter Property="Header" Value="{Binding Name}" />
    <!-- 其他样式配置 -->
</Style>

完整修正后的代码示例

资源部分

<CollectionViewSource x:Key="GroupedProductsSource" 
                      Source="{Binding AAA}">
    <CollectionViewSource.GroupDescriptions>
        <PropertyGroupDescription PropertyName="CategoryName" />
    </CollectionViewSource.GroupDescriptions>
</CollectionViewSource>

页面ItemsControl部分

<ItemsControl ItemsSource="{Binding Source={StaticResource GroupedProductsSource}}" 
              x:Name="CategoriesItemControl"
              Margin="10">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Expander x:Name="CategoryExpander" Header="{Binding Name}">
                <ItemsControl ItemsSource="{Binding Items}"
                              x:Name="GroupedInvoicesItemsControl"
                              Margin="10">
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <Expander Style="{StaticResource ProductExpanderStyle}" 
                                       Tag="{Binding}"
                                       x:Name="ProductExpander"/>
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>
            </Expander>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 21:42:33