1
votes

I have a ListView with two events "ItemTapped" and "ItemSelected" when the user select the item an alert "You selected item" should be appear, and when a user tapped the item an alert "You tapped item" should be appear. but what happened is when the user select an item, first an alert of "You tapped item" is appear then alert of "You selected item" is appear why that happened ???

this is my Xaml file

 <ListView x:Name="listView" 
              ItemTapped="Tapped"
              ItemSelected="Select">
        <ListView.ItemTemplate>
            <DataTemplate>
                <TextCell Text="{Binding Name}" Detail="{Binding Status}"/>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

code behinde

 void Select(object sender, Xamarin.Forms.SelectedItemChangedEventArgs e)
    {
        var contact = e.SelectedItem as Contact;
        DisplayAlert("selected", "You selected item", "Ok");

        // listView.SelectedItem = null;
    }


    void Tapped(object sender, Xamarin.Forms.ItemTappedEventArgs e)
    {
        var contact = e.Item as Contact;
        DisplayAlert("tapped", "You tapped item", "Ok");
    }
4

4 Answers

3
votes

The ItemTapped event is fired when you have tapped an item.

The ItemSelected event is fired when you have selected an item. You select an item when you tap on an item that is currently not selected.

In this case, if you are tapping on an item that is not selected, both the ItemTapped and ItemSelected event will be fired.

1
votes

One workaround is possible to manage both events like, You Can call Listview ItemTapped Event on Double Tap on list item. & By Default Listview Single Tap can get ItemSelected Event.

Note: This is only Workaround to manage both on same time.

1
votes

Another simple workaround can be counting the number of times the Tapped event has been fired. As I realized, the Tapped event always fires before the Selected event, so just define an integer, increase it in each Tapped event, and reset in the Selected event.

private int _myListTapNumber = 0;

...
private void MyList_ItemTapped(object sender, ItemTappedEventArgs e)
{
    if (_myListTapNumber > 1)
    {
        DisplayAlert("Tapped", "Tap event fired.", "OK");
    }
    _myListTapNumber++;
}

private void MyList_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
    _myListTapNumber = 1;

    DisplayAlert("Selected", "Selected event fired.", "OK");
}
-1
votes
private bool selectionFixed = false;
void Select(object sender, SelectedItemChangedEventArgs e)
{
    selectionFixed = false;
}

void Tapped(object sender, ItemTappedEventArgs e)
{
    if (selectionFixed)
        DisplayAlert("Choice", "Your Choice: " + e.Item, "Ok");
    else
        selectionFixed = true;
}