2017-11-25 39 views
0

首先我刚刚开始使用xamarin形式,并且c#我设法使用了listviews,但是当涉及到网格时我有点儿困惑,基本上我需要的是将一个对象绑定到那这样的表现网格意甲:每行xamarin形式的网格人口

2列,我设法与此代码做到这一点:

<Grid HorizontalOptions="Fill" VerticalOptions="Fill" Margin="10"> 
      <Grid.RowDefinitions> 
       <RowDefinition Height="1*" /> 
       <RowDefinition Height="1*" /> 
       <RowDefinition Height="1*" /> 
      </Grid.RowDefinitions> 
      <Grid.ColumnDefinitions> 
       <ColumnDefinition Width="1*" /> 
       <ColumnDefinition Width="1*" /> 
      </Grid.ColumnDefinitions> 

      <!--fila 1--> 
      <StackLayout Grid.Column="0" Grid.Row="0" BackgroundColor="Blue" HorizontalOptions="Fill"></StackLayout> 
      <StackLayout Grid.Column="1" Grid.Row="0" BackgroundColor="Red" HorizontalOptions="Fill"></StackLayout> 
      <!--fila 2--> 
      <StackLayout Grid.Column="0" Grid.Row="1" BackgroundColor="Red" HorizontalOptions="Fill"></StackLayout> 
      <StackLayout Grid.Column="1" Grid.Row="1" BackgroundColor="Blue" HorizontalOptions="Fill"></StackLayout> 
      <!--fila 3--> 
      <StackLayout Grid.Column="0" Grid.Row="2" BackgroundColor="Blue" HorizontalOptions="Fill"></StackLayout> 
       <StackLayout Grid.Column="1" Grid.Row="2" BackgroundColor="Red" 
    HorizontalOptions="Fill"></StackLayout> 
    </Grid> 

enter image description here

但是,我不知道如何与填充网格信息动态。与listview是相当简单的,因为它只有绑定命令,在这里我没有想法,有人可以请我指出正确的方向? 谢谢。

+0

网格是一个布局容器,它不支持数据绑定。您可以使用Grid's Children集合在运行时将控件添加到网格中。 – Jason

+0

@Jason谢谢,我想知道至少我如何使用它,我认为这将使用foreach的,但我不知道! –

回答

0
int row = 0; 
int col = 0; 

// data is a List<string> 
foreach (var text in data) { 
    var label = new Label() { Text = text }; 
    grid.Children.Add(box, col, row); 

    col++; 
    if (col > 1) { 
    col = 0; 
    row++; 
    } 

}