【问题标题】:Retrieve firebase data from binding ListView Xamarin Forms从绑定 ListView Xamarin Forms 中检索 firebase 数据
【发布时间】:2021-02-20 06:20:50
【问题描述】:

我有一个列表视图,我在其中使用助手从 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();
        }

page.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 中放了一个 Button,我想获取书名并在 PostAsync 中使用它,所以我基本上需要获取单个书名并将其放入字符串中。

已经在 helper 中创建了类似的方法:


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


但我不知道如何将书籍属性链接到它们与绑定一起显示的单个视单元,知道吗?

【问题讨论】:

  • 如果GetAllBooks 检索到标题,为什么还需要另一个方法getTitle 来获取标题?
  • getAllBooks 返回一个 List,GetTitle 返回一个字符串
  • 是的,但是该列表包含一个 Book 列表,并且每个 Book 已经有一个 Title 属性。为什么你需要再次检索它,而不是从你已经拥有的书中拉出来?您正在单击列表中的一行,您只想获取该行的书名?
  • 我只想要我正在交互的行中的标题,如果我使用 GetAllBooks,我会得到所有书籍及其属性的列表,而我只想要一个字符串。
  • 不需要再次调用GetAllBooks,您已经拥有ItemsSource中的所有数据

标签: listview firebase-realtime-database xamarin.forms binding


【解决方案1】:

不需要再次从您的服务中获取数据,您已经在列表的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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-03
    • 1970-01-01
    • 2018-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多