我已经为 collectionview 添加了命令SelectionChangedCommand
。SelectedItem
<CollectionView
Margin="0,10,0,0"
BackgroundColor="Transparent"
IsVisible="{Binding Visibility}"
ItemsSource="{Binding ImageItems}"
ItemsLayout="VerticalGrid, 2"
SelectionMode="Single"
SelectionChangedCommand="{Binding ImageItemTappedCommand}"
SelectedItem="{Binding LastImageTappedItem, Mode=TwoWay}"
HeightRequest="{Binding ImageHeight}">
<CollectionView.ItemTemplate>
<DataTemplate>
<StackLayout BackgroundColor="{Binding ImageBGColor}">
ImageItemTapped命令:
public NameMatchViewModel() {
ImageItemTappedCommand = new Command((obj) = >{
try {
//reset the bg color
foreach(var item in ImageItems) {
item.ImageBGColor = Colors.White;
}
NameMatchList imageList = obj as NameMatchList;
if (imageList != null) {
Debug.WriteLine("**not null**");
}
else {
Debug.WriteLine("**null**");
}
int index = ImageItems.IndexOf(imageList);
imageList.ImageBGColor = Color.FromArgb("#0091da");
//Storing name and imageurl to local db
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) {
//If both image and name selected by player startes checking the matching
StartNameMatchCheck(imageList);
}
}
catch(Exception imagetapEx) {
Debug.WriteLine("imagetapEx:>>" + imagetapEx);
}
});
}
但是当我尝试获取 selecteditem 值时,我得到的是 null。对于上述代码,我得到以下异常:
以下行除外:
imageList.ImageBGColor = Color.FromArgb("#0091da");
**null**
12:30:36:070 [0:] imagetapEx:>>System.NullReferenceException: Object reference not set to an instance of an object.
12:30:36:070 at MyProjectName.Model.NameMatchViewModel.<.ctor>b__98_0(Object obj) in E:\My Projects\MAUI\MyProjectName-app-maui\MyProjectName\Model\NameMatchViewModel.cs:line 390
我如何获取选定项目的值?