Xamarin Forms ListView Error when tapping an item

When I encountered this issue, the first thng one does is of course ask Google for the solution. To my surprise however, I didn;t find any. Although I did come across some messages on the Xamarin Foroums regarding the exct same error, the source of the issue was unreleated. There seemed to be an issue with the implementation of the ItemTapped event handler. However, I had no such handler; all I was doing was binding the ListView to an enumerable property of my view model. So what was going on?

If you're a seasoned Xamarin Forms developer, you probably already know. As it turns out, the list items source must be an ICollection so that it can access individual items by index.

Consider the following XAML:

<ListView ItemsSource="{Binding MyItems}">
   <ListView.ItemTemplate>
      <DataTemplate>
         <ViewCell>
            <Label Text="{Binding Title}" />
         </ViewCell>
      </DataTemplate>
   </ListView.ItemTemplate>
</ListView>

That looks fine. No problem there. But now consider the following class that was used to set the BindingContext:

public class MyViewModel
{
   public IEnumerable MyItems
   {
      yield return new Item { Title = "Item 1"; }
      yield return new Item { Title = "Item 2"; }
      yield return new Item { Title = "Item 3"; }
   }
}

Do you see the issue? As mentioned, the ListView needs to be able to get an item from the data source by index. Which, of course, doesn't work if the data source is not an ICollection.

Changing the data source to return an ICollection (for example an array) fixed the issue:

public class MyViewModel
{
   public IEnumerable MyItems
   {
      return new Item[]
      {
         new Item { Title = "Item 1" },
         new Item { Title = "Item 2" },
         new Item { Title = "Item 3" }
      }
   }
}

Hopefully this will save you some time when you encounter the same error.

2 comments

Leave a comment