2017-11-11 123 views
1

我想添加BoxViews在網格格式使用3列和多行。我已經使用xaml和c#文件中的行爲 定義了網格。應該發生什麼是一個BoxView應創建相同數量的圖像,每列3個圖像。動態添加BoxViews到網格[Xamarin.Forms]

感謝,

XAML

<Grid RowSpacing="0" x:Name="scrollBarGrid"> 
    <Grid.RowDefinitions> 
     <RowDefinition Height="50"/> 
     <RowDefinition Height="*"/> 
    </Grid.RowDefinitions> 

    <!--Where the search bar will go--> 
    <BoxView BackgroundColor="Aqua" Grid.Row="0"/> 

     <SearchBar ></SearchBar>  

     <!--Where the images will go--> 
    <BoxView BackgroundColor="Gray" Grid.Row="1"/> 
    <Grid x:Name="imageGrid" RowSpacing="0" Grid.Row="1"> 

    </Grid> 

</Grid> 

C#

public MainPage() 
    { 
     InitializeComponent(); 

     int colMaximum = 3; 
     int numberOfImages = 15; 

     //To add three columns 
     for (int i = 0; i < colMaximum; i++) 
     { 
      imageGrid.ColumnDefinitions.Add(new ColumnDefinition() 
      { 
       Width = new GridLength(120, GridUnitType.Absolute) 
      }); 
     } 

     //To add an array of rows 
     imageGrid.RowDefinitions = new RowDefinitionCollection(); 

     for (int myCount = 0; myCount <= numberOfImages/colMaximum; myCount++) 
     { 
      imageGrid.RowDefinitions.Add(new RowDefinition() 
      { 
       Height = new GridLength(120, GridUnitType.Absolute) 
      }); 

      //To add a new box view for each 
      for (int newcol = 0; newcol <= colMaximum; newcol++) 
      { 
       for (int newrow = 0; newrow <= numberOfImages/colMaximum; newrow++) 
       { 
        imageGrid.Children.Add(new BoxView() { BackgroundColor = Color.Red }); 
       } 
      } 
     } 
    } 
+0

你的代碼有什麼問題?它沒有做什麼,或者做得不正確? – Jason

+0

嗨賈森,我想要它做的是打印與變量'numberOfImages'(所以15)相同數量的框。我正在嘗試創建一個類似Instagram的UI,其中頁面將讀取要以網格格式顯示的圖像數量。無論如何,你會知道更好的方法來實現這一點,謝謝。 – Noel625

+0

你說的是你的要求,但你的代碼實際上在做什麼?你有錯誤或異常?它是否打印錯誤的項目數量?它是否做任何事情? – Jason

回答

0

當您添加的孩子一個網格,你必須指定Row和Col,否則他們將在0添加,0。

imageGrid.Children.Add(new BoxView() { BackgroundColor = Color.Red }, newrow, newcol);