如何在嵌套CollectionView的Expander内容中绑定数据?
解决方案
1. 修正绑定路径错误
在Expander.Content内的CollectionView,当前数据上下文是单个DCBStepsList实例,而非ViewModel中的groupStepsModel集合。因此绑定路径应直接指向当前对象的Names属性,而非groupStepsModel.Names:
<toolkit:Expander.Content> <CollectionView ItemsSource="{Binding Names}" ItemTemplate="{StaticResource Key=CustomTemplateDCB}"> </CollectionView> </toolkit:Expander.Content>
2. 将Names集合替换为ObservableCollection
原代码中DCBStepsList的Names是List<Person>,它未实现INotifyCollectionChanged接口,后续动态增删集合元素时UI无法自动更新。建议替换为ObservableCollection<Person>:
public class DCBStepsList : INotifyPropertyChanged { public DCBStepsList() { // 初始化改为ObservableCollection Names = new ObservableCollection<Person>(); } // ... 其他属性保持不变 // 修改类型为ObservableCollection<Person> public ObservableCollection<Person> Names { get; set; } }
添加数据时同步调整集合类型:
groupStepsModel.Add( new DCBStepsList() { Description = stepItem.Description, WorkInstructionTitle = stepItem.Description, Id = stepItem.Id, Names = new ObservableCollection<Person> { new Person { Age = 21 }, new Person { Age = 21 } } });
3. 验证ItemTemplate正确性
确保CustomTemplateDCB能正确渲染Person对象属性,例如显示Age的模板示例:
<DataTemplate x:Key="CustomTemplateDCB"> <Label Text="{Binding Age}" FontSize="16" Margin="10"/> </DataTemplate>
完成以上修改后,Expander展开时即可正常显示对应分组的子项列表。
内容的提问来源于stack exchange,提问作者sham
相关产品推荐
相关产品推荐

