ABOUT ME

-

  • [WPF] Grid Row & Column
    Programming/C# 2020. 3. 26. 22:22

    WPF에서 Grid 컨트롤을 분할하는 방법을 알아보겠습니다.

     

    XAML에서 하는 방법은 아래와 같습니다.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="1*"/>
                <RowDefinition Height="2*"/>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="1*"/>
                <ColumnDefinition Width="2*"/>
            </Grid.ColumnDefinitions>
     
            <Grid Grid.Row="0" Grid.Column="0" Background="Red"/>
            <Grid Grid.Row="1" Grid.Column="1" Background="Green"/>
        </Grid>
     

    cs에서 하는 방법은 아래와 같습니다.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
                RowDefinition gridRow1 = new RowDefinition();
                gridRow1.Height = new GridLength(1GridUnitType.Star);
                RowDefinition gridRow2 = new RowDefinition();
                gridRow1.Height = new GridLength(2GridUnitType.Star);
     
                ColumnDefinition gridCol1 = new ColumnDefinition();
                gridCol1.Width = new GridLength(1GridUnitType.Star);
                ColumnDefinition gridCol2 = new ColumnDefinition();
                gridCol2.Width = new GridLength(2GridUnitType.Star);
     
                grid.RowDefinitions.Add(gridRow1);
                grid.RowDefinitions.Add(gridRow2);
     
                Grid subGrid1 = new Grid() { Background = new SolidColorBrush(Colors.Red) };
                Grid.SetRow(subGrid1, 0);
                Grid.SetColumn(subGrid1, 0);
                grid.Children.Add(subGrid1);
     
                Grid subGrid2 = new Grid() { Background = new SolidColorBrush(Colors.Green) };
                Grid.SetRow(subGrid2, 1);
                Grid.SetColumn(subGrid2, 1);
                grid.Children.Add(subGrid2);
     
    cs

    위 두 가지 방식은 Grid에 적용 시 아래와 같이 동일하게 나타납니다.

     

    추가적으로 Grid의 Row 값과 Column 값으로 컨트롤을 찾는 방법입니다.

     

    아래와 같이 하면 빨간색 그리드(subGrid1)를 가져올 수 있습니다.

    1
                UIElement ul = grid.Children.Cast<UIElement>().FirstOrDefault(uie => Grid.GetRow(uie) == 0 && Grid.GetColumn(uie) == 0);
     

    아래와 같이 하면 녹색 그리드(subGrid2)를 가져올 수 있습니다.

    1
                UIElement ul = grid.Children.Cast<UIElement>().FirstOrDefault(uie => Grid.GetRow(uie) == 1 && Grid.GetColumn(uie) == 1);
     

    위에서 Grid.GetRow(uie) == ? 과 Grid.GetColumn(uie) == ?의 조건을 바꿔서 원하는 컨트롤을 가져올 수 있습니다.

     

    *원하는 위치에 아무것도 없을 경우 null을 리턴합니다.

    *여러 개가 있을 경우 처음에 들어간 항목이 리턴됩니다.

    'Programming > C#' 카테고리의 다른 글

    LiveCharts  (0) 2020.04.27
    Build Event Dll Copy !  (0) 2020.04.07
    Summary !  (0) 2020.03.20
    [WPF] .xaml region  (0) 2020.03.20
    [WPF] WindowChrome !  (0) 2020.03.20

    댓글

Designed by Tistory.