以编程方式将视图添加到Xamarin.Forms网格(示例)

・3 分钟阅读

在Xamarin.Forms Xaml中,通过指定行,列跨度和行跨度,可以轻松地将子级添加到网格中。

XAML示例:


<Grid>
 <Grid.RowDefinitions>
 <RowDefinition Height="60" />
 <RowDefinition Height="auto" />
 </Grid.RowDefinitions>

 <Grid.ColumnDefinitions>
 <ColumnDefinition Width="100" />
 <ColumnDefinition Width=".2*" />
 <ColumnDefinition Width=".2*" />
 <ColumnDefinition Width=".5*" />
 <ColumnDefinition Width=".1*" />
 </Grid.ColumnDefinitions> 

 <Label Text="Hello" Grid.Row="0" Grid.Column="0" />
 <Label Text="World" Grid.Row="0" Grid.Column="1" Grid.ColumnSpan="3" />
 <Label Text="From Albuquerque, NM" Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="5" />
</Grid>

关于IGridList < T > 的笔记

IGridList


Add(View view, int left, int top);
Add(View view, int left, int right, int top, int bottom);

参数映射到行,列,行跨距和列跨值,因此:


IGridList<T>.Add(view, left, top) == Grid.Children.Add(view, column, row);
IGridList<T>.Add(view, left, right, top, bottom) == Grid.Children.Add(view, column, column+columnSpan, row, row+rowSpan);

C#示例


var grid = new Grid
 {
 RowDefinitions =
 {
 new RowDefinition { Height = new GridLength(60, GridUnitType.Absolute) }, 
 new RowDefinition { Height = GridLength.Auto }, 
 }, ColumnDefinitions =
 {
 new ColumnDefinition { Width = new GridLength(100, GridUnitType.Absolute) }, 
 new ColumnDefinition { Width = new GridLength(.2, GridUnitType.Star) },
 new ColumnDefinition { Width = new GridLength(.2, GridUnitType.Star) },
 new ColumnDefinition { Width = new GridLength(.5, GridUnitType.Star) },
 new ColumnDefinition { Width = new GridLength(.1, GridUnitType.Star) }
 }
 };


//if right and bottom aren't specified, the column and row spans will be 1 
grid.Children.Add(new Label{Text="Hello"}, 0, 0);

//to start at column 1 and span 4 columns, right needs to be column + column span; 1 + 4 = 5. Since this overload requires values for top and bottom, the row (top) is 0, and the row span is 1; 0 + 1 = 1, so bottom must be 1.
grid.Children.Add(new Label{Text="World"}, 1, 5, 0, 1);

//column (left) = 0, right = column + column span; 0 + 5 = 6. row (top) = 1, bottom = row + row span; 1 + 1 = 2
grid.Children.Add(new Label{Text="From Albuquerque, NM"}, 0, 6, 1, 2);
Jiaoyang75 profile image