Xamarin.Forms 그리드

Download Sample 샘플 다운로드

Xamarin.Forms Grid

Grid 식을 행과 열로 구성하는 레이아웃으로, 비례 또는 절대 크기를 가질 수 있습니다. 기본적으로 Grid에는 하나의 행과 하나의 열이 포함됩니다. 또한 다른 Grid 자식 레이아웃을 포함하는 부모 레이아웃으로 사용할 수 있습니다.

레이아웃은 Grid 테이블과 혼동해서는 안 되며 테이블 형식 데이터를 표시하기 위한 것이 아닙니다. HTML 테이블과 달리 콘텐츠 Grid 배치를 위한 것입니다. 테이블 형식 데이터를 표시하려면 ListView, CollectionView 또는 TableView를 사용하는 것이 좋습니다.

Grid 클래스는 다음 속성을 정의합니다.

  • Column- 부모 Grid내에서 뷰의 열 맞춤을 나타내는 연결된 속성인 형식int입니다. 이 속성의 기본값은 0입니다. 유효성 검사 콜백은 속성이 설정되면 해당 값이 0보다 크거나 같은지 확인합니다.
  • ColumnDefinitions형식 ColumnDefinitionCollection의 눈금 열 너비를 정의하는 개체 목록 ColumnDefinition 입니다.
  • ColumnSpacing형식 double의 눈금 열 사이의 거리를 나타냅니다. 이 속성의 기본값은 6 디바이스 독립적 단위입니다.
  • ColumnSpan- 부모 내에서 Grid뷰에 걸쳐 있는 열의 총 수를 나타내는 연결된 속성인 형식int입니다. 이 속성의 기본값은 1입니다. 유효성 검사 콜백은 속성이 설정되면 해당 값이 1보다 크거나 같은지 확인합니다.
  • Row- 부모 Grid내에서 뷰의 행 맞춤을 나타내는 연결된 속성인 형식int입니다. 이 속성의 기본값은 0입니다. 유효성 검사 콜백은 속성이 설정되면 해당 값이 0보다 크거나 같은지 확인합니다.
  • RowDefinitions형식 RowDefinitionCollection의 눈금 행의 RowDefintion 높이를 정의하는 개체 목록입니다.
  • RowSpacing형식 double의 눈금 행 사이의 거리를 나타냅니다. 이 속성의 기본값은 6 디바이스 독립적 단위입니다.
  • RowSpan- 부모 내에서 Grid뷰에 걸쳐 있는 행의 총 수를 나타내는 연결된 속성인 형식int입니다. 이 속성의 기본값은 1입니다. 유효성 검사 콜백은 속성이 설정되면 해당 값이 1보다 크거나 같은지 확인합니다.

이러한 속성은 개체에 의해 BindableProperty 지원됩니다. 즉, 속성이 데이터 바인딩의 대상이 될 수 있으며 스타일이 지정될 수 있습니다.

클래스는 Grid 형식IList<T>Layout<T> 속성을 정의하는 클래스에서 파생됩니다Children. 속성은 ChildrenContentProperty 클래스이므로 Layout<T> XAML에서 명시적으로 설정할 필요가 없습니다.

최상의 레이아웃 성능을 얻으려면 레이아웃 성능 최적화의 지침을 따르세요.

행 및 열

기본적으로 하나의 Grid 행과 하나의 열이 포함됩니다.

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="GridTutorial.MainPage">
    <Grid Margin="20,35,20,20">
        <Label Text="By default, a Grid contains one row and one column." />
    </Grid>
</ContentPage>

이 예제에서는 Grid 단일 위치에 자동으로 배치되는 단일 자식 Label 이 포함됩니다.

Screenshot of a default Grid layout

레이아웃 동작 Grid 은 각각 컬렉션 RowDefinition 및 개체인 속성과 ColumnDefinitionsColumnDefinition 속성을 사용하여 RowDefinitions 정의할 수 있습니다. 이러한 컬렉션은 행과 열의 Grid특성을 정의하며, 각 행에 대해 하나의 RowDefinition 개체와 각 열 Grid에 대해 하나의 ColumnDefinition 개체를 Grid포함해야 합니다.

클래스는 RowDefinition 형식의 속성을 정의 Height 하고 클래스는 ColumnDefinition 형식GridLengthGridLength의 속성을 정의합니다Width. 이 구조체는 GridLength 세 개의 멤버가 있는 열거형 측면에서 GridUnitType 행 높이 또는 열 너비를 지정합니다.

  • Absolute – 행 높이 또는 열 너비는 디바이스 독립적 단위의 값(XAML의 숫자)입니다.
  • Auto – 행 높이 또는 열 너비는 셀 내용(Auto XAML)에 따라 자동으로 조정됩니다.
  • Star – 남은 행 높이 또는 열 너비가 비례적으로 할당됩니다(XAML 뒤에 숫자 * ).

Grid 속성이 있는 Height 행은 해당 행의 Auto 뷰 높이를 세StackLayout로와 같은 방식으로 제한합니다. 마찬가지로 속성이 있는 열은 WidthAuto 가로 StackLayout와 매우 유사합니다.

주의

가능한 한 적은 수의 행과 열이 크기로 설정되어 있는지 확인합니다 Auto . 자동으로 크기가 조정된 행이나 열은 레이아웃 엔진이 추가적인 레이아웃 계산을 수행하도록 합니다. 가능한 경우 고정된 크기의 행과 열을 대신 사용하세요. 또는 열거형 값을 사용하여 비례 공간의 양을 차지하도록 행과 GridUnitType.Star 열을 설정합니다.

다음 XAML에서는 행 3개와 열 2개를 사용하여 만드는 Grid 방법을 보여 줍니다.

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="GridDemos.Views.BasicGridPage"
             Title="Basic Grid demo">
   <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="2*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="100" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        ...
    </Grid>
</ContentPage>

이 예제에서는 Grid 페이지의 높이인 전체 높이를 가집니다. 세 Grid 번째 행의 높이가 디바이스 독립적 단위 100개임을 알고 있습니다. 자체 높이에서 높이를 빼고, 별 앞의 숫자에 따라 첫 번째 행과 두 번째 행 사이에 비례하여 다시 기본 높이를 할당합니다. 이 예제에서 첫 번째 행의 높이는 두 번째 행의 두 배입니다.

ColumnDefinition 개체는 모두 Width*1*화면 너비가 두 열 아래에 균등하게 나뉩니다.

Important

기본값은 RowDefinition.Height 속성은 *합니다. 마찬가지로 속성의 기본값은 ColumnDefinition.Width .입니다 *. 따라서 이러한 기본값이 허용되는 경우 이러한 속성을 설정할 필요가 없습니다.

자식 뷰는 연결된 속성과 함께 특정 Grid 셀에 Grid.Column 배치할 수 Grid.Row 있습니다. 또한 자식 뷰가 여러 행과 열에 걸쳐 있도록 하려면 연결된 속성과 Grid.ColumnSpan 속성을 사용합니다Grid.RowSpan.

다음 XAML은 동일한 Grid 정의를 보여 줍니다. 또한 자식 뷰를 특정 Grid 셀에 배치합니다.

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="GridDemos.Views.BasicGridPage"
             Title="Basic Grid demo">
   <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="2*" />
            <RowDefinition />
            <RowDefinition Height="100" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <BoxView Color="Green" />
        <Label Text="Row 0, Column 0"
               HorizontalOptions="Center"
               VerticalOptions="Center" />
        <BoxView Grid.Column="1"
                 Color="Blue" />
        <Label Grid.Column="1"
               Text="Row 0, Column 1"
               HorizontalOptions="Center"
               VerticalOptions="Center" />
        <BoxView Grid.Row="1"
                 Color="Teal" />
        <Label Grid.Row="1"
               Text="Row 1, Column 0"
               HorizontalOptions="Center"
               VerticalOptions="Center" />
        <BoxView Grid.Row="1"
                 Grid.Column="1"
                 Color="Purple" />
        <Label Grid.Row="1"
               Grid.Column="1"
               Text="Row1, Column 1"
               HorizontalOptions="Center"
               VerticalOptions="Center" />
        <BoxView Grid.Row="2"
                 Grid.ColumnSpan="2"
                 Color="Red" />
        <Label Grid.Row="2"
               Grid.ColumnSpan="2"
               Text="Row 2, Columns 0 and 1"
               HorizontalOptions="Center"
               VerticalOptions="Center" />
    </Grid>
</ContentPage>

참고 항목

및 속성은 Grid.Row 모두 0에서 인덱싱되므로 Grid.Row="2" 두 번째 열을 참조하는 동안 Grid.Column="1" 세 번째 행을 참조 Grid.Column 합니다. 또한 이러한 두 속성의 기본값은 0이므로 첫 번째 행 또는 첫 번째 열을 Grid차지하는 자식 뷰에서 설정할 필요가 없습니다.

이 예제에서는 세 Grid 행이 모두 뷰에 의해 BoxViewLabel 점유됩니다. 세 번째 행은 디바이스 독립적 단위가 100개이고 처음 두 행은 재기본 공간(첫 번째 행은 두 번째 행보다 두 배 높음)을 차지합니다. 두 열은 너비가 같고 반으로 Grid 나눕니다. BoxView 세 번째 행의 두 열에 걸쳐 있습니다.

Screenshot of a basic Grid layout

또한 셀을 공유할 수 있는 자식 뷰도 Grid 있습니다. 자식이 XAML에 표시되는 순서는 자식이 배치되는 순서입니다 Grid. 이전 예제에서는 개체가 Label 개체 위에 BoxView 렌더링되기 때문에 개체만 볼 수 있습니다. 개체를 Label 맨 위에 렌더링하면 BoxView 개체가 표시되지 않습니다.

해당하는 C# 코드는 다음과 같습니다.

public class BasicGridPageCS : ContentPage
{
    public BasicGridPageCS()
    {
        Grid grid = new Grid
        {
            RowDefinitions =
            {
                new RowDefinition { Height = new GridLength(2, GridUnitType.Star) },
                new RowDefinition(),
                new RowDefinition { Height = new GridLength(100) }
            },
            ColumnDefinitions =
            {
                new ColumnDefinition(),
                new ColumnDefinition()
            }
        };

        // Row 0
        // The BoxView and Label are in row 0 and column 0, and so only needs to be added to the
        // Grid.Children collection to get default row and column settings.
        grid.Children.Add(new BoxView
        {
            Color = Color.Green
        });
        grid.Children.Add(new Label
        {
            Text = "Row 0, Column 0",
            HorizontalOptions = LayoutOptions.Center,
            VerticalOptions = LayoutOptions.Center
        });

        // This BoxView and Label are in row 0 and column 1, which are specified as arguments
        // to the Add method.
        grid.Children.Add(new BoxView
        {
            Color = Color.Blue
        }, 1, 0);
        grid.Children.Add(new Label
        {
            Text = "Row 0, Column 1",
            HorizontalOptions = LayoutOptions.Center,
            VerticalOptions = LayoutOptions.Center
        }, 1, 0);

        // Row 1
        // This BoxView and Label are in row 1 and column 0, which are specified as arguments
        // to the Add method overload.
        grid.Children.Add(new BoxView
        {
            Color = Color.Teal
        }, 0, 1, 1, 2);
        grid.Children.Add(new Label
        {
            Text = "Row 1, Column 0",
            HorizontalOptions = LayoutOptions.Center,
            VerticalOptions = LayoutOptions.Center
        }, 0, 1, 1, 2); // These arguments indicate that that the child element goes in the column starting at 0 but ending before 1.
                        // They also indicate that the child element goes in the row starting at 1 but ending before 2.

        grid.Children.Add(new BoxView
        {
            Color = Color.Purple
        }, 1, 2, 1, 2);
        grid.Children.Add(new Label
        {
            Text = "Row1, Column 1",
            HorizontalOptions = LayoutOptions.Center,
            VerticalOptions = LayoutOptions.Center
        }, 1, 2, 1, 2);

        // Row 2
        // Alternatively, the BoxView and Label can be positioned in cells with the Grid.SetRow
        // and Grid.SetColumn methods.
        BoxView boxView = new BoxView { Color = Color.Red };
        Grid.SetRow(boxView, 2);
        Grid.SetColumnSpan(boxView, 2);
        Label label = new Label
        {
            Text = "Row 2, Column 0 and 1",
            HorizontalOptions = LayoutOptions.Center,
            VerticalOptions = LayoutOptions.Center
        };
        Grid.SetRow(label, 2);
        Grid.SetColumnSpan(label, 2);

        grid.Children.Add(boxView);
        grid.Children.Add(label);

        Title = "Basic Grid demo";
        Content = grid;
    }
}

코드에서 개체의 RowDefinition 높이와 개체의 너비를 ColumnDefinition 지정하려면 구조체의 GridLength 값을 열거형과 함께 GridUnitType 사용합니다.

위의 예제 코드에서는 자식을 추가하고 자식 Grid이 있는 셀을 지정하는 여러 가지 방법도 보여 줍니다. 왼쪽, 오른쪽, 위쪽아래쪽 인수를 지정하는 오버로드를 사용하는 Add 경우 왼쪽위쪽 인수는 항상 내Grid의 셀을 참조하고 오른쪽 아래쪽 인수는 외부Grid에 있는 셀을 참조하는 것처럼 보입니다. 오른쪽 인수는 항상 왼쪽 인수보다 커야 하고 아래쪽 인수는 항상 위쪽 인수보다 커야 하기 때문입니다. 2x2 Grid를 가정하는 다음 예제에서는 두 오버로드를 Add 사용하는 동일한 코드를 보여 줍니다.

// left, top
grid.Children.Add(topLeft, 0, 0);           // first column, first row
grid.Children.Add(topRight, 1, 0);          // second column, first tow
grid.Children.Add(bottomLeft, 0, 1);        // first column, second row
grid.Children.Add(bottomRight, 1, 1);       // second column, second row

// left, right, top, bottom
grid.Children.Add(topLeft, 0, 1, 0, 1);     // first column, first row
grid.Children.Add(topRight, 1, 2, 0, 1);    // second column, first tow
grid.Children.Add(bottomLeft, 0, 1, 1, 2);  // first column, second row
grid.Children.Add(bottomRight, 1, 2, 1, 2); // second column, second row

참고 항목

또한 자식 뷰는 단일 행 또는 단일 열GridGridAddHorizontal 자식을 추가하는 with 및 AddVertical 메서드에 추가할 수 있습니다. 그런 Grid 다음 이러한 호출이 이루어지면 행 또는 열에서 확장되고 올바른 셀에 자식이 자동으로 배치됩니다.

행 및 열 정의 단순화

XAML에서는 각 행과 열에 Grid 대해 정의 RowDefinition 및 개체를 방지할 수 있는 간소화된 구문을 사용하여 행 및 ColumnDefinition 열 특성을 지정할 수 있습니다. 대신 RowDefinitionsColumnDefinitions 쉼표로 구분된 GridUnitType 값을 포함하는 문자열로 속성을 설정할 수 있습니다. 이 문자열에서 형식 변환기는 만들기 RowDefinitionColumnDefinition 개체에 Xamarin.Forms 기본 제공됩니다.

<Grid RowDefinitions="1*, Auto, 25, 14, 20"
      ColumnDefinitions="*, 2*, Auto, 300">
    ...
</Grid>

이 예제에서는 Grid 5개의 행과 4개의 열이 있습니다. 세 번째, 앞, 다섯 번째 행은 절대 높이로 설정되며 두 번째 행은 콘텐츠에 맞게 자동 크기 조정됩니다. 다시 기본 높이가 첫 번째 행에 할당됩니다.

다음 열은 절대 너비로 설정되며 세 번째 열은 내용에 맞게 자동 크기 조정됩니다. re기본ing 너비는 별 앞의 숫자에 따라 첫 번째 열과 두 번째 열 사이에 비례적으로 할당됩니다. 이 예제에서 두 번째 열의 너비는 첫 번째 열의 두 배입니다(동일하기 1*때문*).

행과 열 사이의 공백

기본적으로 Grid 행은 6개의 디바이스 독립적 공간 단위로 구분됩니다. 마찬가지로 Grid 열은 6개의 디바이스 독립적 공간 단위로 구분됩니다. 이러한 기본값은 각각 및 ColumnSpacing 속성을 설정 RowSpacing 하여 변경할 수 있습니다.

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="GridDemos.Views.GridSpacingPage"
             Title="Grid spacing demo">
    <Grid RowSpacing="0"
          ColumnSpacing="0">
        ..
    </Grid>
</ContentPage>

이 예제에서는 행과 열 사이에 간격이 없는 공백을 만듭니다 Grid .

Screenshot of Grid with no spacing between cells

RowSpacingColumnSpacing 속성을 음수 값으로 설정하여 셀 내용이 겹치도록 할 수 있습니다.

해당하는 C# 코드는 다음과 같습니다.

public GridSpacingPageCS()
{
    Grid grid = new Grid
    {
        RowSpacing = 0,
        ColumnSpacing = 0,
        // ...
    };
    // ...

    Content = grid;
}

맞춤

a의 자식 뷰는 Grid 해당 셀 내에서 및 VerticalOptions 속성으로 HorizontalOptions 배치할 수 있습니다. 이러한 속성은 구조체에서 다음 필드로 LayoutOptions 설정할 수 있습니다.

Important

AndExpands 구조체의 LayoutOptions 필드는 개체에 StackLayout 만 적용됩니다.

다음 XAML은 9개의 같은 크기의 셀을 만들고 Grid 서로 다른 맞춤을 사용하여 각 셀에 배치합니다 Label .

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="GridDemos.Views.GridAlignmentPage"
             Title="Grid alignment demo">
    <Grid RowSpacing="0"
          ColumnSpacing="0">
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition />
            <RowDefinition />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>

        <BoxView Color="AliceBlue" />
        <Label Text="Upper left"
               HorizontalOptions="Start"
               VerticalOptions="Start" />
        <BoxView Grid.Column="1"
                 Color="LightSkyBlue" />
        <Label Grid.Column="1"
               Text="Upper center"
               HorizontalOptions="Center"
               VerticalOptions="Start"/>
        <BoxView Grid.Column="2"
                 Color="CadetBlue" />
        <Label Grid.Column="2"
               Text="Upper right"
               HorizontalOptions="End"
               VerticalOptions="Start" />
        <BoxView Grid.Row="1"
                 Color="CornflowerBlue" />
        <Label Grid.Row="1"
               Text="Center left"
               HorizontalOptions="Start"
               VerticalOptions="Center" />
        <BoxView Grid.Row="1"
                 Grid.Column="1"
                 Color="DodgerBlue" />
        <Label Grid.Row="1"
               Grid.Column="1"
               Text="Center center"
               HorizontalOptions="Center"
               VerticalOptions="Center" />
        <BoxView Grid.Row="1"
                 Grid.Column="2"
                 Color="DarkSlateBlue" />
        <Label Grid.Row="1"
               Grid.Column="2"
               Text="Center right"
               HorizontalOptions="End"
               VerticalOptions="Center" />
        <BoxView Grid.Row="2"
                 Color="SteelBlue" />
        <Label Grid.Row="2"
               Text="Lower left"
               HorizontalOptions="Start"
               VerticalOptions="End" />
        <BoxView Grid.Row="2"
                 Grid.Column="1"
                 Color="LightBlue" />
        <Label Grid.Row="2"
               Grid.Column="1"
               Text="Lower center"
               HorizontalOptions="Center"
               VerticalOptions="End" />
        <BoxView Grid.Row="2"
                 Grid.Column="2"
                 Color="BlueViolet" />
        <Label Grid.Row="2"
               Grid.Column="2"
               Text="Lower right"
               HorizontalOptions="End"
               VerticalOptions="End" />
    </Grid>
</ContentPage>

이 예제에서는 각 행의 Label 개체가 모두 동일하게 세로로 정렬되지만 다른 가로 맞춤을 사용합니다. 또는 각 열의 개체가 가로로 동일하게 정렬되지만 다른 세로 Label 맞춤을 사용하는 것으로 간주할 수 있습니다.

Screenshot of cell alignment within a Grid

해당하는 C# 코드는 다음과 같습니다.

public class GridAlignmentPageCS : ContentPage
{
    public GridAlignmentPageCS()
    {
        Grid grid = new Grid
        {
            RowSpacing = 0,
            ColumnSpacing = 0,
            RowDefinitions =
            {
                new RowDefinition(),
                new RowDefinition(),
                new RowDefinition()
            },
            ColumnDefinitions =
            {
                new ColumnDefinition(),
                new ColumnDefinition(),
                new ColumnDefinition()
            }
        };

        // Row 0
        grid.Children.Add(new BoxView
        {
            Color = Color.AliceBlue
        });
        grid.Children.Add(new Label
        {
            Text = "Upper left",
            HorizontalOptions = LayoutOptions.Start,
            VerticalOptions = LayoutOptions.Start
        });

        grid.Children.Add(new BoxView
        {
            Color = Color.LightSkyBlue
        }, 1, 0);
        grid.Children.Add(new Label
        {
            Text = "Upper center",
            HorizontalOptions = LayoutOptions.Center,
            VerticalOptions = LayoutOptions.Start
        }, 1, 0);

        grid.Children.Add(new BoxView
        {
            Color = Color.CadetBlue
        }, 2, 0);
        grid.Children.Add(new Label
        {
            Text = "Upper right",
            HorizontalOptions = LayoutOptions.End,
            VerticalOptions = LayoutOptions.Start
        }, 2, 0);

        // Row 1
        grid.Children.Add(new BoxView
        {
            Color = Color.CornflowerBlue
        }, 0, 1);
        grid.Children.Add(new Label
        {
            Text = "Center left",
            HorizontalOptions = LayoutOptions.Start,
            VerticalOptions = LayoutOptions.Center
        }, 0, 1);

        grid.Children.Add(new BoxView
        {
            Color = Color.DodgerBlue
        }, 1, 1);
        grid.Children.Add(new Label
        {
            Text = "Center center",
            HorizontalOptions = LayoutOptions.Center,
            VerticalOptions = LayoutOptions.Center
        }, 1, 1);

        grid.Children.Add(new BoxView
        {
            Color = Color.DarkSlateBlue
        }, 2, 1);
        grid.Children.Add(new Label
        {
            Text = "Center right",
            HorizontalOptions = LayoutOptions.End,
            VerticalOptions = LayoutOptions.Center
        }, 2, 1);

        // Row 2
        grid.Children.Add(new BoxView
        {
            Color = Color.SteelBlue
        }, 0, 2);
        grid.Children.Add(new Label
        {
            Text = "Lower left",
            HorizontalOptions = LayoutOptions.Start,
            VerticalOptions = LayoutOptions.End
        }, 0, 2);

        grid.Children.Add(new BoxView
        {
            Color = Color.LightBlue
        }, 1, 2);
        grid.Children.Add(new Label
        {
            Text = "Lower center",
            HorizontalOptions = LayoutOptions.Center,
            VerticalOptions = LayoutOptions.End
        }, 1, 2);

        grid.Children.Add(new BoxView
        {
            Color = Color.BlueViolet
        }, 2, 2);
        grid.Children.Add(new Label
        {
            Text = "Lower right",
            HorizontalOptions = LayoutOptions.End,
            VerticalOptions = LayoutOptions.End
        }, 2, 2);

        Title = "Grid alignment demo";
        Content = grid;
    }
}

중첩된 Grid 개체

A는 Grid 중첩된 자식 개체 또는 다른 자식 Grid 레이아웃을 포함하는 부모 레이아웃으로 사용할 수 있습니다. 개체를 중첩할 Grid 때 , Grid.ColumnGrid.Row, Grid.RowSpanGrid.ColumnSpan 연결된 속성은 항상 부모 Grid내에서 뷰의 위치를 참조합니다.

다음 XAML은 중첩 Grid 개체의 예를 보여줍니다.

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:converters="clr-namespace:GridDemos.Converters"
             x:Class="GridDemos.Views.ColorSlidersGridPage"
             Title="Nested Grids demo">

    <ContentPage.Resources>
        <converters:DoubleToIntConverter x:Key="doubleToInt" />

        <Style TargetType="Label">
            <Setter Property="HorizontalTextAlignment"
                    Value="Center" />
        </Style>
    </ContentPage.Resources>

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>

        <BoxView x:Name="boxView"
                 Color="Black" />
        <Grid Grid.Row="1"
              Margin="20">
            <Grid.RowDefinitions>
                <RowDefinition />
                <RowDefinition />
                <RowDefinition />
                <RowDefinition />
                <RowDefinition />
                <RowDefinition />
            </Grid.RowDefinitions>
            <Slider x:Name="redSlider"
                    ValueChanged="OnSliderValueChanged" />
            <Label Grid.Row="1"
                   Text="{Binding Source={x:Reference redSlider},
                                  Path=Value,
                                  Converter={StaticResource doubleToInt},
                                  ConverterParameter=255,
                                  StringFormat='Red = {0}'}" />
            <Slider x:Name="greenSlider"
                    Grid.Row="2"
                    ValueChanged="OnSliderValueChanged" />
            <Label Grid.Row="3"
                   Text="{Binding Source={x:Reference greenSlider},
                                  Path=Value,
                                  Converter={StaticResource doubleToInt},
                                  ConverterParameter=255,
                                  StringFormat='Green = {0}'}" />
            <Slider x:Name="blueSlider"
                    Grid.Row="4"
                    ValueChanged="OnSliderValueChanged" />
            <Label Grid.Row="5"
                   Text="{Binding Source={x:Reference blueSlider},
                                  Path=Value,
                                  Converter={StaticResource doubleToInt},
                                  ConverterParameter=255,
                                  StringFormat='Blue = {0}'}" />
        </Grid>
    </Grid>
</ContentPage>

이 예제에서 루트 Grid 레이아웃에는 첫 번째 행의 자 BoxView 식과 두 번째 행의 자식 Grid 이 포함됩니다. 자식 Grid 에는 Slider 다음과 같이 표시되는 색 BoxView을 조작하는 개체와 LabelSlider값이 표시되는 개체가 포함됩니다.

Screenshot of nested Grids

Important

개체 및 기타 레이아웃을 중첩 Grid 할수록 중첩된 레이아웃이 성능에 더 많이 영향을 줍니다. 자세한 내용은 올바른 레이아웃 선택을 참조 하세요.

해당하는 C# 코드는 다음과 같습니다.

public class ColorSlidersGridPageCS : ContentPage
{
    BoxView boxView;
    Slider redSlider;
    Slider greenSlider;
    Slider blueSlider;

    public ColorSlidersGridPageCS()
    {
        // Create an implicit style for the Labels
        Style labelStyle = new Style(typeof(Label))
        {
            Setters =
            {
                new Setter { Property = Label.HorizontalTextAlignmentProperty, Value = TextAlignment.Center }
            }
        };
        Resources.Add(labelStyle);

        // Root page layout
        Grid rootGrid = new Grid
        {
            RowDefinitions =
            {
                new RowDefinition(),
                new RowDefinition()
            }
        };

        boxView = new BoxView { Color = Color.Black };
        rootGrid.Children.Add(boxView);

        // Child page layout
        Grid childGrid = new Grid
        {
            Margin = new Thickness(20),
            RowDefinitions =
            {
                new RowDefinition(),
                new RowDefinition(),
                new RowDefinition(),
                new RowDefinition(),
                new RowDefinition(),
                new RowDefinition()
            }
        };

        DoubleToIntConverter doubleToInt = new DoubleToIntConverter();

        redSlider = new Slider();
        redSlider.ValueChanged += OnSliderValueChanged;
        childGrid.Children.Add(redSlider);

        Label redLabel = new Label();
        redLabel.SetBinding(Label.TextProperty, new Binding("Value", converter: doubleToInt, converterParameter: "255", stringFormat: "Red = {0}", source: redSlider));
        Grid.SetRow(redLabel, 1);
        childGrid.Children.Add(redLabel);

        greenSlider = new Slider();
        greenSlider.ValueChanged += OnSliderValueChanged;
        Grid.SetRow(greenSlider, 2);
        childGrid.Children.Add(greenSlider);

        Label greenLabel = new Label();
        greenLabel.SetBinding(Label.TextProperty, new Binding("Value", converter: doubleToInt, converterParameter: "255", stringFormat: "Green = {0}", source: greenSlider));
        Grid.SetRow(greenLabel, 3);
        childGrid.Children.Add(greenLabel);

        blueSlider = new Slider();
        blueSlider.ValueChanged += OnSliderValueChanged;
        Grid.SetRow(blueSlider, 4);
        childGrid.Children.Add(blueSlider);

        Label blueLabel = new Label();
        blueLabel.SetBinding(Label.TextProperty, new Binding("Value", converter: doubleToInt, converterParameter: "255", stringFormat: "Blue = {0}", source: blueSlider));
        Grid.SetRow(blueLabel, 5);
        childGrid.Children.Add(blueLabel);

        // Place the child Grid in the root Grid
        rootGrid.Children.Add(childGrid, 0, 1);

        Title = "Nested Grids demo";
        Content = rootGrid;
    }

    void OnSliderValueChanged(object sender, ValueChangedEventArgs e)
    {
        boxView.Color = new Color(redSlider.Value, greenSlider.Value, blueSlider.Value);
    }
}