我有一个循环,为每位患者的StackLayout添加一个网格(大约70条记录)。网格有一个图片列(其源是一个url)和一个名称列。我认为这些图片导致了内存不足的情况,但经过几个小时的踩踏代码后,我偶然发现了什么似乎是罪魁祸首。如果我将网格包裹在一个框架中,这似乎是一个问题。我正在使用Xamarin 4.2.1.62。
我确实想要每个病人周围都有一个框架,所以我可以围绕每个病人设置边框。有人有主意吗?
对于可重现的示例,请创建一个包含单个StackLayout的页面
<StackLayout VerticalOptions="FillAndExpand" x:Name="StackPatientList"></StackLayout>
然后,在页面中的InitializeComponent()调用之后,调用此函数:
private void InitPatients()
{
ObservableCollection<Patient> PatientsList = new ObservableCollection<Patient>();
for (int i = 0; i < 100; i++)
{
PatientsList.Add(new Patient() { FirstName = "First " + i.ToString(), LastName = "Last " + i.ToString() });
}
StackLayout oStack = new StackLayout() { };
this.StackPatientList.Children.Clear();
foreach (Patient oPat in PatientsList)
{
Grid oGrid = new Grid();
oGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(100, GridUnitType.Auto) });
oGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) });
oGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(100, GridUnitType.Absolute) });
oGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
Image oPatImage = new Image() { Source = oPat.Picture, WidthRequest = 100, HeightRequest = 100 };
Label oPatLabel = new Label() { Text = oPat.FullName, FontSize = 15, VerticalTextAlignment = TextAlignment.Center };
oGrid.Children.Add(oPatLabel, 0, 0);
oGrid.Children.Add(oPatImage, 1, 0);
Frame oFrame = new Frame() { OutlineColor = Color.Black, Padding = 5, VerticalOptions = LayoutOptions.FillAndExpand };
oFrame.Content = oGrid;
//this.StackPatientList.Children.Add(oGrid); // Using this works fine
this.StackPatientList.Children.Add(oFrame); // This causes an out of memory error
}
}
将此作为您的患者类:
public class Patient
{
public string LastName { get; set; }
public string FirstName { get; set; }
public string FullName { get { return LastName + ", " + FirstName; } }
public string Picture { get; set; }
}
在Android设备上运行它(我使用LG-G3),你会得到一个内存不足的错误。然后注释掉添加框架的行并取消注释只添加网格的行,它将正常工作。