首页 > 解决方案 > xamarin 表单中从 firebase 到 listView 的数据

问题描述

我有这个从 firebase 带来数据的任务:

public async Task<List<Player>> GetPlayersData()
        {
            var playersData = (await client.Child("Players")
                .OnceAsync<Player>())
                .Select(f => new Player
                {
                    PlayerName = f.Object.PlayerName,
                    PlayerTime = f.Object.PlayerTime,
                    PlayerRank = f.Object.PlayerRank
                }).ToList();
            return playersData;
        }

它工作得很好,但我想让(playersData)把它作为XAML中“Listview”中的“ItemSource”,所以我在页面构造函数中调用任务:

public RankTable()
        {
            InitializeComponent();
            BindingContext = this;
            client = new FirebaseClient("https://numbergame-*****firebaseio.com/");

            GetPlayersData();
        }  

现在它将运行任务并带来玩家数据,但我不知道如何控制它并将其作为 ItemSource 放在以下 XAML 代码中:

<StackLayout>

            <CollectionView Grid.ColumnSpan="2" Grid.RowSpan="2" SelectionMode="None" ItemsSource="{Binding ??}">
            <CollectionView.ItemTemplate>
                <DataTemplate>

                        <Frame HasShadow="True" BackgroundColor="Beige" CornerRadius="15"
                               IsClippedToBounds="True" Visual="Material" InputTransparent="True">
                        <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition/>
                            <ColumnDefinition/>
                            <ColumnDefinition/>
                            
                        </Grid.ColumnDefinitions>
                        <Label Text="{Binding PlayerRank}" FontSize="15" Grid.Column="1"/>
                        <Label Text="{Binding PlayerName}" FontSize="15" Grid.Column="2"/>
                        <Label Text="{Binding PlayerTime}" FontSize="15" Grid.Column="3"/>
                        
                        </Grid>
                        </Frame>
                    </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>
        </StackLayout>

任何帮助请和对不起我的英语不好..

标签: c#firebasexamlfirebase-realtime-databasexamarin.forms

解决方案


<CollectionView x:Name="Players" ... /

// GetPlayersData is async so you can't call it from the constructor
protected override void OnAppearing()
{
    Players.ItemsSource = await GetPlayersData();
}

推荐阅读