如何在Listview绑定Xamarin.Forms中创建一个网格

如何在ListView中使用数据绑定创建Grid? 我正在用Xamarin.Forms创建这个应用程序。

如果我不知道我需要多少行和列,如何在ListView绑定中动态创建Grid?

这是我到目前为止:

              

在此代码中,只创建了一行和一列。 如果我有多个数据点,我该如何解决这个问题? 例如,如果我需要一行有两列。

提前致谢。

在XAML中动态构建具有可变数量的行或列的Grid布局没有好办法。 我建议在代码隐藏文件中创建DataTemplate,您可以根据需要轻松添加尽可能多的RowDefinitions和ColumnDefinitions。 这是一个例子:

  var myDataTemplate = new DataTemplate(() => { var cell = new ViewCell(); var grid = new Grid(); foreach (var record in myRecords) { grid.RowDefinitions.Add(new RowDefinition()); } foreach (var field in myFields) { grid.ColumnDefinitions.Add(new ColumnDefinition()); } /* * * Populate grid here... * */ cell.View = grid; return cell; }); 

然后将此DataTemplate分配给ListView。

您也可以使用下一个方法示例(通过xaml,正面)。

     #F2F2F2                                 

如果要动态添加行和列,可以在page.cs创建一个网格,并将其绑定到page.xaml 。 假设您有多个项目,并且您想要在网格中对它们进行排序:

 public page() { string[] items = {"Item 1","Item 2",......."Item n"}; var itemsGrid = new Grid(); int k = 1 + items.Length / 3; // just to make it clear in the for loop i used (int k) // suppose 3 column need we divide on 3 // define the number of rows according to the number of item you have for (int i = 0; i