简体   繁体   English

Xamarin Forms ListView ItemSelected功能

[英]Xamarin Forms ListView ItemSelected functionality

Here is a function that gets called when an item gets selected from a ListView : 这是一个从ListView选择项目时调用的函数:

async void detail_clicked(object sender, SelectedItemChangedEventArgs e){
    if (e.SelectedItem == null) {
            return;
    }
    Detail selected = (Detail)e.SelectedItem;
    order_vm.List_of_details.Add(selected);
    await DisplayAlert ("Item Added", 
        String.Format ("{0} added to cart.", selected.detail_name), "Okay");
    ((ListView)sender).SelectedItem = null;
}

I added this function using the ItemSelected event handler 我使用ItemSelected事件处理程序添加了此功能

details_list.ItemSelected += detail_clicked;

The first time I click on the Item, the DisplayAlert pops up. 第一次单击项目时,将弹出DisplayAlert After the first click, the DisplayAlert inside detail_clicked no longer pops up. 第一次单击后,不再弹出detail_clicked内部的DisplayAlert But the other code inside the handler does get called. 但是处理程序中的其他代码确实会被调用。

Anyone know how to fix this issue? 有人知道如何解决此问题吗? Is it something I am not understanding about event handlers? 我对事件处理程序不了解吗? Is it something about await/async? 关于等待/异步吗?

The DisplayAlert might be running on a different thread. DisplayAlert可能正在其他线程上运行。 Try wrapping Display Alert in Device.BeginInvokeOnMainThread . 尝试将Display Alert包装在Device.BeginInvokeOnMainThread You can ready about that here . 您可以在这里做好准备。

请再次检查方法是否异步,然后在DisplayAlert()上等待。

Use this following code. 使用以下代码。 It will helps you. 它将为您提供帮助。

private void OnItemSelected(object sender, SelectedItemChangedEventArgs e)
    {
        if (e.SelectedItem == null)
        {

            return;

        }

        listView.SelectedItem = null;

        DisplayAlert("Alert", e.SelectedItem.ToString(), "Ok");

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM