.NET MAUI中CollectionView嵌套SwipeView刷新时仅Windows端崩溃
问题:Windows端刷新购物车时程序崩溃(Android正常)
首次加载购物车内容正常,但刷新时程序崩溃,仅Windows端出现该问题,Android端运行无异常。移除SwipeView后程序恢复正常,即使针对Windows平台禁用SwipeView仍会触发崩溃。
相关XAML代码
<CollectionView ItemsSource="{Binding Cart}" SelectionMode="Multiple" SelectedItems="{Binding SelectedItemsInCart}" SelectionChanged="On_SelectionChanged" EmptyView="No ingredients in your cart" x:Name="collectionView" HorizontalOptions="Center"> <CollectionView.ItemTemplate> <DataTemplate> <SwipeView> <SwipeView.RightItems> <SwipeItems > <SwipeItem Text="Delete" IconImageSource="trash.png" BackgroundColor="LightPink" Command="{Binding RemoveFromCartCommand}" CommandParameter="{Binding}" /> </SwipeItems> </SwipeView.RightItems> <Grid RowDefinitions="auto, auto" x:DataType="model:Ingredient"> <Label Grid.Row="0" Text="{Binding Name}" FontAttributes="Bold" FontSize="20" HorizontalOptions="Center"/> <Label Grid.Row="1" Text="{Binding Quantity}" FontSize="15" HorizontalOptions="Center"/> </Grid> </SwipeView> </DataTemplate> </CollectionView.ItemTemplate> </CollectionView>
报错信息
Unhandled exception at 0x00007FFB117CE1EF (combase.dll) in CookUs.exe: 0xC0000602: A FailFast exception has occurred. Exception handlers will not be called and the process will terminate immediately.
解决方案
- 确认
SelectedItemsInCart的集合类型:必须使用ObservableCollection,Windows端对SelectedItems绑定的集合类型兼容性要求更高,普通List 在刷新时易引发底层COM错误。 - 优化SelectionChanged事件处理:如果
On_SelectionChanged中有修改Cart集合的逻辑,改用Dispatcher异步执行,避免UI线程死锁:private void On_SelectionChanged(object sender, SelectionChangedEventArgs e) { Dispatcher.Dispatch(() => { // 原集合修改逻辑 }); } - 修正SwipeItem的Command绑定:通过RelativeSource引用ViewModel的命令,避免Item级绑定在刷新时失效:
<SwipeItem Text="Delete" IconImageSource="trash.png" BackgroundColor="LightPink" Command="{Binding DataContext.RemoveFromCartCommand, RelativeSource={RelativeSource AncestorType={x:Type CollectionView}}}" CommandParameter="{Binding}" /> - 刷新前重置选中项:更新Cart集合前先清空
SelectedItemsInCart,避免旧选中项与新数据不匹配导致异常:SelectedItemsInCart.Clear(); Cart = new ObservableCollection<Ingredient>(updatedCartData); - 升级MAUI版本:该问题可能是MAUI Windows平台的已知Bug,升级到最新稳定版可修复部分底层COM交互问题。
内容的提问来源于stack exchange,提问作者user20564490
相关产品推荐
相关产品推荐

