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
相关产品推荐
相关产品推荐

