Fio
Fio

Reputation: 43

Retrieve firebase data from binding ListView Xamarin Forms

I have a listview where I retrieve data from firebase with an helper and show it by binding them in .xaml, like that:

the helper:

public class FirebaseHelper
public async Task<List<Books>> GetAllBooks()
        {
            return (await firebase
              .Child("Books")
              .OnceAsync<Books>()).Select(item => new Books
              {
                  Title = item.Object.Title,
                  Author = item.Object.Author,
                  Genre = item.Object.Genre,
                  Cover  = item.Object.Cover
              }).ToList();
        }

the page.xaml.cs

public List<Books> libriall;

protected async override void OnAppearing()
        { 
            base.OnAppearing();
            bookall = await firebaseHelper.GetAllBooks();
            listbook.ItemsSource = bookall;
        }

and a part of the listview listbook in the .xaml file:

<Label 
       TextColor="#33272a"
       Text="{Binding Title}"
       x:Name="bTitle"/>

Ok now I put a Button in the ViewCell and I want to get the book title and use it in a PostAsync, so I basically need to get the single title book and put it in a string.

Already created a method like that in the helper:


public async Task<string> getTitle()
        {
            return (await firebase
              .Child("Books")
              .OnceAsync<Books>()).Select(item => new Books
              {
                  Title = item.Title
              }).ToString();
        }


But I don't know how to link books properties to the single viewcell they are displayed with the binding, any idea?

Upvotes: 1

Views: 543

Answers (1)

Jason
Jason

Reputation: 89204

you do not need to get the data from your service again, you already have it in the ItemsSource for your list

void ButtonClicked(object sender, EventArgs args)
{
  Button btn = (Button)sender;

  // the BindingContext of the Button will be the Books
  // object for the row you clicked on 
  var book = (Books)btn.BindingContext;

  // now you can access all of the properties of Books
  var title = book.Title;
}

Upvotes: 2

Related Questions