Passing arguments to ListView.ItemTapped

I have a ListView containing instances of an own made class Post.
I want to pass a member of Post as an argument in an ItemTapped event.

      <ListView  x:Name="Post_list" RowHeight="150" ItemTapped="Post_list_ItemTapped">
            <SearchBar VerticalOptions="Center" HorizontalOptions="End" HeightRequest="50" TextColor="Black" CancelButtonColor="White" Placeholder="Search" TextChanged="SearchBar_TextChanged" x:Name="Searchbar"/>
                  <StackLayout BackgroundColor="White" Spacing="1">
                     <Grid BackgroundColor="White" HeightRequest="150" >
                        <Label Text = "{Binding Title}" FontSize="16" HorizontalOptions="Center" VerticalTextAlignment="Center" HorizontalTextAlignment="Center" TextColor="#303030" FontFamily="Arial"/>
                        <Label Text = "{Binding PublishTime}" FontSize="10" FontFamily="Arial" TextColor="#303030" VerticalTextAlignment="Start" HorizontalTextAlignment="End" TranslationX="-15"/>
                        <Label Text = "{Binding Price, StringFormat ='{0:F0} SEK'}" FontSize="16" FontFamily="Arial" TextColor="#F22140" VerticalTextAlignment="Center" HorizontalTextAlignment="End" WidthRequest="90" TranslationX="-15"/>
                        <Image Source="book.jpg" HorizontalOptions="Start" VerticalOptions="Center" WidthRequest="120" HeightRequest="120"/>

I've set the contents of the ListView like such:
Post_list.ItemsSource = postList;
Where postList is a List<Post>

And after looking at a turtorial i should be able to pass arguments like this:

    private void Post_list_ItemTapped(object sender, ItemTappedEventArgs e)
        Post tappedPost = (Post)sender;
        Navigation.PushModalAsync(new MarketItemPage(tappedPost.Id, tappedPost.UserId));                

The issue is i get a cast exception, which means sender is not a Post.

Anyone got any ideas?

Best Answer


  • 15mgm1515mgm15 USMember ✭✭✭✭

    I think is similar to this:

    void OnSelection (object sender, SelectedItemChangedEventArgs e)
      if (e.SelectedItem == null) {
        return; //ItemSelected is called on deselection, which results in SelectedItem being set to null
      DisplayAlert ("Item Selected", e.SelectedItem.ToString (), "Ok");
      //((ListView)sender).SelectedItem = null; //uncomment line if you want to disable the visual selection state.

    which e.SelectedItem can be casted to your object: (Post)

  • magic67magic67 USMember ✭✭✭

    @arminmosaffaie You could also use the HandleNavigation action from your reference 'Post_List' like this

        Post_List.HandleNavigation<postList>(async (item) =>
            Navigation.PushAsync(new MarketItemPage(item.Id, item.UserId)); 

    I would also add the Listview source in the XAML like this
    <ListView x:Name="Post_list" RowHeight="150" ItemsSource="postList">

    or if your using a VM - ItemsSource="Binding Items"

Sign In or Register to comment.