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

MAUI CollectionView的SelectionChangedCommand获取选中项为null问题

解决CollectionView SelectionChangedCommand获取选中项为null的问题

问题原因

默认情况下,CollectionView的SelectionChangedCommand传递的参数是SelectionChangedEventArgs类型,而非选中的项本身,直接将参数转为NameMatchList自然会得到null,进而触发空引用异常。

解决方案一:直接使用绑定的SelectedItem

你已经通过SelectedItem="{Binding LastImageTappedItem, Mode=TwoWay}"绑定了选中项,直接在命令中使用这个属性即可,这种方式更可靠:

  1. 确保ViewModel中LastImageTappedItem属性实现INotifyPropertyChanged:
private NameMatchList _lastImageTappedItem;
public NameMatchList LastImageTappedItem
{
    get => _lastImageTappedItem;
    set 
    {
        _lastImageTappedItem = value;
        OnPropertyChanged(); // 需实现INotifyPropertyChanged接口
    }
}
  1. 修改命令实现:
public NameMatchViewModel() 
{
    ImageItemTappedCommand = new Command(() =>
    {
        try 
        {
            if (LastImageTappedItem == null) return;
            
            // 重置所有项背景色
            foreach(var item in ImageItems) 
            {
                item.ImageBGColor = Colors.White;
            }
            
            NameMatchList imageList = LastImageTappedItem;
            Debug.WriteLine("**选中项不为空**");
            
            imageList.ImageBGColor = Color.FromArgb("#0091da");
            
            // 存储数据到Preferences
            if (Utility.IsInternet()) 
            {
                Preferences.Default.Set("NameMatchImageList_Image", imageList.imageUrl);
            }
            else 
            {
                Preferences.Default.Set("NameMatchImageList_Image", imageList.FullImageUrl);
            }
            Preferences.Default.Set("NameMatchImageList_Name", imageList.name);
            Preferences.Default.Set("ImageItem", imageList);
            
            isImageSelected = true;
            if (isImageSelected && isNameSelected) 
            {
                StartNameMatchCheck(imageList);
            }
        }
        catch(Exception imagetapEx) 
        {
            Debug.WriteLine("imagetapEx:>>" + imagetapEx);
        }
    });
}

解决方案二:显式传递选中项作为命令参数

通过XAML绑定,将CollectionView的SelectedItem直接作为命令参数传递:

  1. 修改XAML中的CollectionView配置:
<CollectionView
    Margin="0,10,0,0"
    BackgroundColor="Transparent"
    IsVisible="{Binding Visibility}"
    ItemsSource="{Binding ImageItems}"
    ItemsLayout="VerticalGrid, 2"
    SelectionMode="Single"
    SelectionChangedCommand="{Binding ImageItemTappedCommand}"
    SelectionChangedCommandParameter="{Binding Source={RelativeSource Self}, Path=SelectedItem}"
    SelectedItem="{Binding LastImageTappedItem, Mode=TwoWay}"
    HeightRequest="{Binding ImageHeight}">
  1. 命令实现可保留原有结构,但需先判空:
public NameMatchViewModel() 
{
    ImageItemTappedCommand = new Command((obj) =>
    {
        try 
        {
            NameMatchList imageList = obj as NameMatchList;
            if (imageList == null) return;
            
            // 重置所有项背景色
            foreach(var item in ImageItems) 
            {
                item.ImageBGColor = Colors.White;
            }
            
            Debug.WriteLine("**选中项不为空**");
            imageList.ImageBGColor = Color.FromArgb("#0091da");
            
            // 存储数据到Preferences
            if (Utility.IsInternet()) 
            {
                Preferences.Default.Set("NameMatchImageList_Image", imageList.imageUrl);
            }
            else 
            {
                Preferences.Default.Set("NameMatchImageList_Image", imageList.FullImageUrl);
            }
            Preferences.Default.Set("NameMatchImageList_Name", imageList.name);
            Preferences.Default.Set("ImageItem", imageList);
            
            isImageSelected = true;
            if (isImageSelected && isNameSelected) 
            {
                StartNameMatchCheck(imageList);
            }
        }
        catch(Exception imagetapEx) 
        {
            Debug.WriteLine("imagetapEx:>>" + imagetapEx);
        }
    });
}

内容的提问来源于stack exchange,提问作者Matthew Pans

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 22:52:41