从异步任务表填充堆栈布局



我通过异步任务从 api 获取数据:

public async Task<PostModel.Post[]> GetPostsAsync()
    {
        var client = new HttpClient();
        var uri = new Uri("link here");
        var response = await client.GetAsync(uri);
        if (response.IsSuccessStatusCode)
        {
            var jsonString = await response.Content.ReadAsStringAsync();
            var rootObject = JsonConvert.DeserializeObject<PostModel.Post[]>(jsonString);
            return rootObject;
        }
        else
            return null;
    }

此外,我还创建了一个简单的垂直视图:

<ContentPage.Content>
    <ListView x:Name="MainView">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <StackLayout Orientation="Vertical" HorizontalOptions="Fill" VerticalOptions="Fill" BackgroundColor="WhiteSmoke">
                        <Frame OutlineColor="Black">
                            <Label x:Name="Title" Text="{Binding Name}"/>
                            <Image x:Name="Image" Source="{Binding path}" />
                        </Frame>
                    </StackLayout>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</ContentPage.Content>

编写了用于显示数据的自定义单元格:

 public CustomCell()
    {
        //instantiate items in views
        var Image = new Image();
        var NameLabel = new Label();
        var horizontalLayout = new StackLayout() { BackgroundColor = Color.WhiteSmoke };
        //set bindings
        NameLabel.SetBinding(Label.TextProperty, new Binding("Name"));
        Image.SetBinding(Image.SourceProperty, new Binding("path"));
        Image.HorizontalOptions = LayoutOptions.Center;
        Image.HeightRequest = 600;
        Image.WidthRequest = 600;
        NameLabel.FontSize = 24;
        //add views to the view hierarchy
        horizontalLayout.Children.Add(NameLabel);
        horizontalLayout.Children.Add(Image);
        //add to parent view
        View = horizontalLayout;
    }

现在我想动态填充异步任务中的布局。例如,如果任务获得 6 个项目,则使用来自每个异步任务项目的数据创建 6 个单元格。任何建议我该怎么做?我在xamarin.forms中完全是绿色的,刚刚开始尝试。

在 OnAppearing 中,只需为 ListView 设置源即可

MainView.ItemSource = await GetPostsAsync();

相关内容

  • 没有找到相关文章

最新更新