我正在使用標準 Android 模擬器在 Visual Studio 2019 中開發 Xamarin Forms 應用程式。XAML 包含一個包含網格的 ScrollView。網格只有兩列。我有一個用于連接到資料庫的 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.xaml.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");
}
}
}
}
uj5u.com熱心網友回復:
以垂直方向的 StackLayout 環繞網格。Grid 沒有在 ScrollView 內擴展。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/329452.html
標籤:沙马林 xamarin.forms
