Xamarin Android模拟器在滚动视图中使用网格,只绘制网格的第一页



我正在使用标准的Android模拟器在Visual Studio 2019中开发Xamarin Forms应用程序。XAML包含一个ScrollView,其中包含一个Grid。网格只有两列。我有一个OnStart事件的处理程序,它连接到数据库,获得包含64个对象的响应,为每个对象向网格添加两个标签,并填充标签。ScrollView的背景色设置为黄色。当我使用模拟器调试应用程序时,初始屏幕被正确绘制。但是当我向下滚动时,网格没有被填充。背景仍然是黄色的,表明滚动视图的大小是正确的(或者至少足够大,可以容纳更多的标签)。我做错了什么?

当我在第二个for循环的底部放置一个断点时,在添加标签之后,我看到我有了我所期望的所有标签对象,并且它们具有我所期望的文本属性。

这里是XAML:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="CapsBases.MainPage">
<ScrollView BackgroundColor="Yellow"
VerticalOptions="FillAndExpand">
<Grid Margin="10"
x:Name="BasesGrid">
<!-- two columns:  base ID and status -->
<Grid.ColumnDefinitions>
<ColumnDefinition Width="60" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
</Grid>
</ScrollView>
</ContentPage>

事件处理程序调用mainpage . example .cs文件中名为ShowBases()的函数。

public async void ShowBases()
{
string url = "http://10.0.2.2:5000/caps/bases";
//HttpClient client = new HttpClient();
//string info = await client.GetStringAsync(url);
//// await DisplayAlert("Coil Count", message, "Close");
//// The base ID and string will be returned in a single string with a space separating them.
//string[] pieces = info.Split(' ');
//BaseID.Text = pieces[0];
//BaseStatus.Text = pieces[1];
using (HttpClient client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
string data = await response.Content.ReadAsStringAsync();
//IEnumerable<Base> baseList = JsonConvert.DeserializeObject<IEnumerable<Base>>(data);
List<Base> baseList = JsonConvert.DeserializeObject<List<Base>>(data).OrderBy(b =>b.BaseName).ToList();
//BaseID.Text = theBase.BaseName;
//BaseStatus.Text = theBase.Status;
string message = $"Retrieved {baseList.Count()} bases.";
await DisplayAlert("Result", message, "Close");
Grid theGrid = BasesGrid;
var rowDefinitions = theGrid.RowDefinitions;
for (int i = 0; i < baseList.Count(); i++)
{
RowDefinition rowDef = new RowDefinition { Height = 20 };
rowDefinitions.Add(rowDef);
}
await DisplayAlert("Row count", $"The grid has {BasesGrid.RowDefinitions.Count()} rows.", "Close");
// We have the grid with all the rows we need.  Now we have to create a label for each grid cell.
try
{
for (int i = 0; i < baseList.Count(); i++)
{
BasesGrid.Children.Add
(
new Label
{
Text = baseList[i].BaseName,
HorizontalOptions = LayoutOptions.Start
},
0, i
);
BasesGrid.Children.Add
(
new Label
{
Text = baseList[i].Status,
HorizontalOptions = LayoutOptions.Start
},
1, i
);
}
}
catch (Exception ex)
{
await DisplayAlert("Error", $"Failed to add row data: {ex.Message}", "Close");
}
}
else
{
await DisplayAlert("Get Coils failure",
$"Failed to retrieve coils; status code: {response.StatusCode}",
"Close");
}
}
}

}

在垂直方向的StackLayout中包围网格。网格没有在ScrollView中展开。