Xamarin加载CollectionView时出现无效强制转换,页面崩溃
CollectionView加载时崩溃,报错在
View = (View)template.CreateContent(); 我有一个CollectionView,原本要加载对象的所有属性,但打开页面时应用直接崩溃,崩溃发生在代码行View = (View)template.CreateContent();。已确认Libraries集合已正确填充数据,不存在空数据问题。
绑定方法代码
public void Bind(object itemBindingContext, ItemsView itemsView, Action<Size> reportMeasure = null, Size? size = null) { var template = _template.SelectDataTemplate(itemBindingContext, itemsView); var templateChanging = template != _selectedTemplate; if (templateChanging) { // Clean up any content we're still holding on to _itemContentView.Recycle(); // Create the new content View = (View)template.CreateContent(); // Set the binding context _before_ we create the renderer; that way, the bound data will be // available during OnElementChanged View.BindingContext = itemBindingContext; // Make sure the Visual property is available when the renderer is created PropertyPropagationExtensions.PropagatePropertyChanged(null, View, itemsView); // Actually create the native renderer _itemContentView.RealizeContent(View); _selectedTemplate = template; } _itemContentView.HandleItemSizingStrategy(reportMeasure, size); if (!templateChanging) { // Same template, new data View.BindingContext = itemBindingContext; } itemsView.AddLogicalChild(View); }
CollectionView的XAML代码
<CollectionView VerticalScrollBarVisibility="Always" Margin="0,10,20,0" ItemsSource="{Binding Libraries}" VerticalOptions="StartAndExpand" HeightRequest="210"> <CollectionView.ItemsLayout> <LinearItemsLayout Orientation="Vertical"/> </CollectionView.ItemsLayout> <CollectionView.ItemTemplate> <DataTemplate> <ViewCell> <Grid Margin="8,0"> <Grid.RowDefinitions> <RowDefinition Height="*"/> <RowDefinition Height="auto"/> </Grid.RowDefinitions> <sh:Shadows Margin="0,0,0,5" Shades="{sh:SingleShade Opacity=0.4, BlurRadius=10, Color=Black}" CornerRadius="100"> <Frame Grid.Column="0" BackgroundColor="#D9D9D9" HorizontalOptions="Center" VerticalOptions="Center" Padding="0" CornerRadius="100" WidthRequest="150" HeightRequest="150" IsClippedToBounds="True"> <Image x:Name="userImage" Source="{Binding Picture, Converter={StaticResource ByteArrayToImageConverter}}" WidthRequest="{OnPlatform iOS=100, Android=100}" HorizontalOptions="Center"/> </Frame> </sh:Shadows> <StackLayout Grid.Column="1" Margin="10,0,0,0"> <Label Text="{Binding Name, TargetNullValue='Sconosciuto'}" FontFamily="Inter" FontAttributes="Bold" MaxLines="3" LineBreakMode="TailTruncation" FontSize="16" HorizontalOptions="Start" TextColor="Black" Margin="0,0,10,0"/> <Label Text="{Binding Address, TargetNullValue='Sconosciuto'}" FontFamily="Inter" FontSize="13" HorizontalOptions="Start" TextColor="#D9D9D9"/> </StackLayout> </Grid> </ViewCell> </DataTemplate> </CollectionView.ItemTemplate> </CollectionView>
ViewModel加载Libraries的代码
public LoanBookPageViewModel(Book book) { Book = book; Libraries = BookService.GetLibrariesWithAvailableBook(Book); }
可能的解决方向
- 移除ViewCell:CollectionView的ItemTemplate不需要包裹ViewCell(这是ListView的用法),直接将Grid作为DataTemplate的根元素。ViewCell会导致
template.CreateContent()返回的不是View类型,强制转换失败引发崩溃。 - 检查模板选择逻辑:确认
_template.SelectDataTemplate返回的DataTemplate有效,未返回null或非View类型的模板。 - 转换器异常处理:给
ByteArrayToImageConverter添加空值判断和异常捕获逻辑,避免转换无效字节数组时抛出异常,导致模板创建过程崩溃。 - 异步加载数据:如果
BookService.GetLibrariesWithAvailableBook是同步耗时操作,改成异步加载,加载完成后再更新Libraries集合,避免UI线程阻塞引发异常。
内容的提问来源于stack exchange,提问作者spoooooooonman
相关产品推荐
相关产品推荐

