c# - 在 Xamarin.Forms 中动态创建网格
问题描述
我目前正在使用一个测试应用程序来列出例如产品,但存在无法使用相应内容动态生成网格的问题(目前只有标签)。我想在调用 Mainpage 时立即生成它们。
我已经浏览了各种教程和网站,但找不到任何可以帮助我解决问题的东西。尝试通过将其分配给按钮来启动创建网格的方法。我尝试将方法分配给 MainPage 类的构造函数,但最终结果中仍然没有显示任何内容。
public void CreateDummyGrids()
{
Grid gOut = new Grid();
gOut.RowDefinitions.Add(new RowDefinition());
gOut.RowDefinitions.Add(new RowDefinition());
gOut.RowDefinitions.Add(new RowDefinition());
gOut.ColumnDefinitions.Add(new ColumnDefinition());
gOut.ColumnDefinitions.Add(new ColumnDefinition());
for (int rowIndex = 0; rowIndex < 3; rowIndex++)
{
for (int columnIndex = 0; columnIndex < 2; columnIndex++)
{
var label = new Label
{
Text ="Hello",
VerticalOptions = LayoutOptions.Center,
HorizontalOptions = LayoutOptions.Center
};
gOut.Children.Add(label, columnIndex, rowIndex);
}
}
}
解决方案
这Grid gOut
是您CreateDummyGrids
方法的局部变量,不会传递给其他任何地方。所以在方法之后它会被破坏。
您需要在 XAML 中有某种元素来添加网格(或者只是将网格放在那里并直接将子元素添加到其中)。
因此,在您希望网格出现的地方添加如下内容:
<Grid x:Name="productGrid" />
并将您的更改CreateDummyGrids
为:
public void CreateDummyGrids()
{
productGrid.RowDefinitions.Add(new RowDefinition());
productGrid.RowDefinitions.Add(new RowDefinition());
productGrid.RowDefinitions.Add(new RowDefinition());
productGrid.ColumnDefinitions.Add(new ColumnDefinition());
productGrid.ColumnDefinitions.Add(new ColumnDefinition());
for (int rowIndex = 0; rowIndex < 3; rowIndex++)
{
for (int columnIndex = 0; columnIndex < 2; columnIndex++)
{
var label = new Label
{
Text ="Hello",
VerticalOptions = LayoutOptions.Center,
HorizontalOptions = LayoutOptions.Center
};
productGrid.Children.Add(label, columnIndex, rowIndex);
}
}
}
现在请记住,每次调用此方法时都会添加新的 ColumnDefinitions、RowDefinitions 和 Labels,因此如果您想继续添加内容,则必须稍微更改设置。但我希望这足以让你朝着正确的方向前进