我通过异步任务从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中完全是绿色的,并且刚开始尝试它。