如何选择项目 MVVM listview - Xamarin 表单
Posted
技术标签:
【中文标题】如何选择项目 MVVM listview - Xamarin 表单【英文标题】:How selected item MVVM listview - Xamarin form 【发布时间】:2020-08-04 00:13:34 【问题描述】:如何在 listview Mvvm 中选择项目我的代码不起作用
我的代码项目来源:
protected async override void OnAppearing()
base.OnAppearing();
var allPersons = await firebaseHelper.GetAllCamps();
lstCampus.ItemsSource = allPersons;
我的代码选择项:
void OnItemTapped(object sender, System.EventArgs e)
if (lstCampus.SelectedItem != null)
DisplayAlert("OnItemTapped", lstCampus.SelectedItem.ToString(), "OK");
我的模型:
public class Campus
public string NameCamp get; set;
我的视图模型:
public async Task<List<Campus>> GetAllCamps()
return (await firebase
.Child("Camps")
.OnceAsync<Campus>()).Select(item => new Campus
NameCamp = item.Object.NameCamp
).ToList();
谢谢你
【问题讨论】:
【参考方案1】:您可以尝试使用行为。这将帮助您:
https://www.c-sharpcorner.com/article/xamarin-forms-eventtocommand-behavior-in-mvvm-viewmodel/
https://docs.microsoft.com/en-US/xamarin/xamarin-forms/app-fundamentals/behaviors/reusable/event-to-command-behavior
之后,只需将这样的内容添加到您的列表中:
<ListView.Behaviors>
<b:EventToCommandBehavior EventName="ItemTapped" Command="Binding TappedCamp" InputConverter="StaticResource ItemTappedConverter"/>
</ListView.Behaviors>
【讨论】:
【参考方案2】:使用List.ItemTapped 或ListView.ItemSelected 事件,当一个项目被选中时它们都会被引发。
ItemTapped
listview.ItemTapped += Listview_ItemTapped;
private void Listview_ItemTapped(object sender, ItemTappedEventArgs e)
DisplayAlert("OnItemTapped", (e.Item as Campus).NameCamp , "OK");
项目选择
listview.ItemSelected += Listview_ItemSelected;
private void Listview_ItemSelected(object sender, SelectedItemChangedEventArgs e)
DisplayAlert("OnItemTapped", (e.SelectedItem as Campus).NameCamp, "OK");
【讨论】:
以上是关于如何选择项目 MVVM listview - Xamarin 表单的主要内容,如果未能解决你的问题,请参考以下文章
Xamarin ListView itemSelected MVVM
如何以编程方式从viewmodel中选择listview项?