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

.NET 8 MAUI中iOS端CollectionView绑定崩溃(安卓/Windows正常)

.NET 8 MAUI CollectionView在iOS端崩溃:Value cannot be null. (Parameter 'key')

问题场景

在.NET 8 MAUI项目中,自定义ContentView(NumberPicker)内的CollectionView绑定到后台的NumberList可绑定属性,安卓和Windows平台运行正常,但iOS端加载视图时直接崩溃,抛出异常:Value cannot be null. (Parameter 'key')。已做测试:

  • 切换集合类型为List,问题依旧
  • 简化ItemTemplate为仅显示文本的Label,问题依旧
  • 替换CollectionView为VerticalStackLayout可正常运行

解决思路

1. 给BindableProperty设置默认值

iOS端对CollectionView的空数据源处理更严格,若NumberList未初始化会导致崩溃。修改可绑定属性的创建代码,添加默认空集合:

public static readonly BindableProperty NumberListProperty =
    BindableProperty.Create(
        nameof(NumberList), 
        typeof(ObservableCollection<int?>), 
        typeof(NumberPicker), 
        defaultValue: new ObservableCollection<int?>() // 添加默认值
    );

public ObservableCollection<int?> NumberList
{
    get { return (ObservableCollection<int?>)GetValue(NumberListProperty); }
    set { SetValue(NumberListProperty, value); }
}

2. 修正RelativeSource绑定的目标类型

XAML中绑定的AncestorType使用ContentView可能不够精准,若NumberPicker是ContentView的子类,应指定为具体的自定义类型(需先在XAML头部声明命名空间,比如xmlns:local="clr-namespace:YourAppNamespace"):

<CollectionView
    VerticalScrollBarVisibility="Never"
    SelectionMode="None"
    ItemsSource="{Binding Source={RelativeSource AncestorType={x:Type local:NumberPicker}}, Path=NumberList}">
    <!-- 模板内容 -->
</CollectionView>

3. 直接绑定到ContentView自身

避免RelativeSource可能的绑定歧义,给ContentView设置名称并直接绑定:

<ContentView x:Class="YourAppNamespace.NumberPicker"
             x:Name="SelfView"
             BindingContext="{x:Reference SelfView}">
    <CollectionView
        VerticalScrollBarVisibility="Never"
        SelectionMode="None"
        ItemsSource="{Binding NumberList}">
        <!-- 模板内容 -->
    </CollectionView>
</ContentView>

4. 在构造函数中确保集合初始化

在NumberPicker的构造函数中添加兜底初始化,防止集合为null:

public NumberPicker()
{
    InitializeComponent();
    NumberList ??= new ObservableCollection<int?>();
}

5. 更新.NET 8 MAUI补丁

检查是否存在.NET 8 MAUI的iOS已知bug,更新到最新的.NET 8服务补丁版本,修复可能的框架层面问题。

内容的提问来源于stack exchange,提问作者Jeremy A.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 19:12:02