如何使用MVVM Toolkit获取ListView选中项数据?
使用CommunityToolkit.Mvvm获取ListView选中项并触发操作
问题场景
需要在点击ListView项时获取选中数据并触发操作(如弹出提示),当前已绑定SelectedItem到ViewModel,但无法触发后续逻辑,尝试过RelayCommand但未生效。
现有XAML代码:
<ListView ItemsSource="{Binding Almacenes}" HasUnevenRows="True" SelectedItem="{Binding SelectedItem}" > <ListView.ItemTemplate> <DataTemplate> <ViewCell> <Grid Padding="20"> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" /> </Grid.ColumnDefinitions> <Image Grid.RowSpan="2" Source="empresita.svg" Aspect="AspectFill" HeightRequest="60" WidthRequest="60" /> <Label Grid.Column="1" Padding="15,0,0,0" Text="{Binding nombre}" FontAttributes="Bold" FontSize="16"/> <Label Grid.Row="1" Padding="15,0,0,0" Grid.Column="1" Text="descripcion" FontAttributes="Italic" VerticalOptions="End" FontSize="16"/> </Grid> </ViewCell> </DataTemplate> </ListView.ItemTemplate> </ListView>
现有ViewModel代码:
[ObservableProperty] List<Almacenes> _almacenes; [ObservableProperty] Almacenes _selectedItem; public SeleccionAlmacenViewModel() { Almacenes = new List<Almacenes>() { new Almacenes() { nombre = "Tomato" }, new Almacenes() { nombre = "Pizza" }, new Almacenes() { nombre = "Romaine" }, }; } public SeleccionAlmacenViewModel(List<Almacenes> almacenes) { Almacenes = new List<Almacenes>(); CargarAlmacenes(almacenes); } private void CargarAlmacenes(List<Almacenes> almacenes) { Almacenes = almacenes; }
解决方案
方案1:利用ObservableProperty的属性变更回调(推荐)
CommunityToolkit.Mvvm会为[ObservableProperty]自动生成partial变更方法,直接重写该方法即可在SelectedItem变化时触发逻辑:
修改ViewModel,添加以下代码:
// 当SelectedItem属性变更时自动触发此方法 partial void OnSelectedItemChanged(Almacenes? oldValue, Almacenes? newValue) { if (newValue != null) { // 执行选中后的操作,示例:弹出提示展示选中项名称 _ = AppShell.Current.DisplayAlert("选中成功", $"你选中了:{newValue.nombre}", "确定"); // 如果需要调用其他RelayCommand,也可以在这里执行 // YourCommand.Execute(newValue); } }
方案2:直接绑定ItemTapped事件到RelayCommand
通过ListView的ItemTappedCommand直接绑定命令,并传递当前项作为参数:
- 修改XAML的ListView,添加命令绑定:
<ListView ItemsSource="{Binding Almacenes}" HasUnevenRows="True" ItemTappedCommand="{Binding ItemSelectedCommand}" ItemTappedCommandParameter="{Binding .}"> <!-- 原有ItemTemplate保持不变 --> </ListView>
- 在ViewModel中添加对应的RelayCommand:
[RelayCommand] public async Task ItemSelected(Almacenes item) { if (item == null) return; // 处理选中逻辑 await AppShell.Current.DisplayAlert("选中成功", $"你选中了:{item.nombre}", "确定"); // 后续业务逻辑写在这里 }
原代码未生效原因
之前尝试的GetAlmacenCommand未绑定到任何UI触发事件,NotifyCanExecuteChangedFor仅用于更新命令的可执行状态,不会自动触发命令执行。需要通过属性变更回调或UI事件绑定来触发命令。
内容的提问来源于stack exchange,提问作者Reyneer Leon
相关产品推荐
相关产品推荐

