Xamarin Forms给ListView加分组部署iOS时触发TargetException
解决Xamarin Forms ListView分组时的类型不匹配错误
这个错误很典型,本质是你给分组ListView的数据源结构不对——ListView开启分组后,期望的是一组包含子项的分组对象,但你可能不小心把单个interpretedObject直接塞进去了,或者数据源的层级搞混了。我给你一步步理清楚怎么修复:
1. 先定义正确的分组类
分组类需要是包含子项的集合,同时要有一个分组标识(比如分组名称/键)。最简单的方式是继承List<T>,同时加个分组键属性:
public class InterpretedObjectGroup : List<interpretedObject> { // 分组的标识,比如按类别、日期分组的键 public string GroupKey { get; set; } // 构造函数:传入分组键和该组的所有子项 public InterpretedObjectGroup(string key, IEnumerable<interpretedObject> items) : base(items) { GroupKey = key; } }
2. 把原始数据转换成分组集合
你需要把你的interpretedObject列表按你想要的规则(比如某个属性)分组,然后包装成上面的分组类实例:
// 假设你有原始的未分组数据 var rawItems = new List<interpretedObject>(); // 这里按你业务里的分组规则来,比如按对象的Category属性分组 var groupedData = rawItems .GroupBy(item => item.Category) // 替换成你的分组字段 .Select(group => new InterpretedObjectGroup(group.Key, group)) .ToList(); // 把分组集合绑定到ListView的ItemsSource MyListView.ItemsSource = groupedData;
3. 检查XAML的分组配置是否正确
确保你的ListView开启了分组,并且正确绑定分组头和子项:
<ListView x:Name="MyListView" IsGroupingEnabled="True"> <!-- 分组头的模板,绑定分组类的GroupKey属性 --> <ListView.GroupHeaderTemplate> <DataTemplate> <ViewCell> <Label Text="{Binding GroupKey}" FontSize="Large" FontAttributes="Bold" Margin="10,5"/> </ViewCell> </DataTemplate> </ListView.GroupHeaderTemplate> <!-- 子项的模板,绑定interpretedObject的属性 --> <ListView.ItemTemplate> <DataTemplate> <ViewCell> <StackLayout Margin="15,5"> <Label Text="{Binding YourObjectProperty}"/> <!-- 其他你需要显示的属性 --> </StackLayout> </ViewCell> </DataTemplate> </ListView.ItemTemplate> </ListView>
为什么会触发这个错误?
大概率是你在准备数据源时犯了这两个错误之一:
- 直接把单个
interpretedObject实例添加到了分组集合里,而不是添加InterpretedObjectGroup类型的分组对象 - 给ListView的ItemsSource绑定了普通的
List<interpretedObject>,同时开启了IsGroupingEnabled="True"——这时候ListView会把每个子项当成一个分组,自然会类型不匹配
按上面的步骤调整后,分组功能应该就能正常工作了。
内容的提问来源于stack exchange,提问作者Alan Mark Kristensen
相关产品推荐
相关产品推荐

