2016-08-19 89 views
1

我是Xamarin.Forms的新手。現在我需要在頁面中設計一個網格,網格是3X2(2行,3列)。但是我需要這個網格中的所有單元格爲正方形,並且此網格的寬度與其父視圖相匹配。使用Xamarin創建一個3X2網格,每個單元格呈方形。表格

換句話說,假設屏幕的寬度(或這個網格的父視圖)是3,那麼每列的寬度是1.我怎樣才能強制每行的高度恰好爲1(so網格中的每個單元的高度等於寬度)?

這是我設計的,但不能工作:

<Grid> 
    <Grid.ColumnDefinitions> 
    <ColumnDefinition Width="*"/> 
    <ColumnDefinition Width="*"/> 
    <ColumnDefinition Width="*"/> 
    </Grid.ColumnDefinitions> 
    <Grid.RowDefinitions> 
    <RowDefinition Height="*"/> 
    <RowDefinition Height="*"/> 
    </Grid.RowDefinitions> 
</Grid> 

是否有純粹的XAML解決這個問題?

謝謝你的幫助。

回答

2

Star調整大小調整自己與可用空間的方向,所以你需要通過重寫OnSizeAllocated方法手動調整(小心嵌套方法調用時調整大小的孩子)。

的XAML:

<Grid x:Name="mainGrid"> 
    <Grid.ColumnDefinitions> 
    <ColumnDefinition Width="*"/> 
    <ColumnDefinition Width="*"/> 
    <ColumnDefinition Width="*"/> 
    </Grid.ColumnDefinitions> 
    <Grid.RowDefinitions> 
    <RowDefinition Height="*"/> 
    <RowDefinition Height="*"/> 
    </Grid.RowDefinitions> 
</Grid> 

Xaml.cs

protected override void OnSizeAllocated(double width, double height) 
{ 
    base.OnSizeAllocated(width, height); 

    if (3 * height > 2 * height) 
     mainGrid.HeightRequest = 2.0/3 * width; 
    else 
     mainGrid.WidthRequest = 3.0/2 * height; 
} 
+1

感謝。但是,我對'if(3 * height> 2 * height)'有點困惑' – Alan

+0

讓我們以一個例子來解釋:如果我們假設每個方形邊緣都是1「,那麼您的容器應該是3」和2「。你的'Grid'應該尊重這個3x2的比例,這個條件檢查我們是否減少'Width'或'Height'。 – Kowalski

0
protected override void OnSizeAllocated(double width, double height) 
{ 
    base.OnSizeAllocated(width, height); 

    double colsCount = MainGrid.ColumnDefinitions.Count; 
    double rowsCount = MainGrid.RowDefinitions.Count; 
    if (colsCount > 0 & rowsCount > 0) 
    { 
     MainGrid.HeightRequest = width/colsCount * rowsCount; 
    } 
} 
相關問題