从绑定ListView Xamarin Forms中检索firebase数据



我有一个列表视图,在那里我用一个助手从firebase中检索数据,并通过将它们绑定到.xaml中来显示,如下所示:

助手:

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();
}

页面.xaml.cs

public List<Books> libriall;
protected async override void OnAppearing()
{ 
base.OnAppearing();
bookall = await firebaseHelper.GetAllBooks();
listbook.ItemsSource = bookall;
}

以及.xaml文件中listview listbook的一部分:

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

好的,现在我在ViewCell中放了一个按钮,我想得到书名并在PostAsync中使用它,所以我基本上需要得到一本书名书并把它放在一个字符串中。

已经在助手中创建了一个类似的方法:


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

但我不知道如何将书籍属性链接到绑定显示的单个视图单元格,知道吗?

不需要再次从服务中获取数据,您的列表的ItemsSource中已经有了数据

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;
}

最新更新