如何为XAML动态创建网格布局

时间:2016-07-03 14:14:06

标签: c# wpf xaml uwp

在我的应用程序中,我正在尝试动态创建网格布局但未获得预期的输出:

以下是我尝试过的代码:

        Grid LayoutGrid = new Grid();


        //Created Two Columns
        ColumnDefinition gridCol1 = new ColumnDefinition();
        ColumnDefinition gridCol2 = new ColumnDefinition();

        LayoutGrid.ColumnDefinitions.Add(gridCol1);
        LayoutGrid.ColumnDefinitions.Add(gridCol2);

        Grid Col1Grid = new Grid();
        //Create Two Rows
        RowDefinition gridRow1 = new RowDefinition();
        RowDefinition gridRow2 = new RowDefinition();

        Col1Grid.RowDefinitions.Add(gridRow1);
        Col1Grid.RowDefinitions.Add(gridRow2);

        Grid.SetColumn(Col1Grid, 1);

        return LayoutGrid;

我想要创建的布局是这样的:

enter image description here

1 个答案:

答案 0 :(得分:0)

我添加了一些颜色以便于理解

private Grid CreateGrid()
    {
        var LayoutGrid = new Grid { Background = new SolidColorBrush(Colors.Yellow) };

        //Created Two Columns
        LayoutGrid.ColumnDefinitions.Add(new ColumnDefinition());
        LayoutGrid.ColumnDefinitions.Add(new ColumnDefinition());

        //Created Two Rows
        LayoutGrid.RowDefinitions.Add(new RowDefinition());
        LayoutGrid.RowDefinitions.Add(new RowDefinition());

        // region 1 - vertical left
        var stack1 = new StackPanel {
            Background = new SolidColorBrush(Colors.Red)
        };
        Grid.SetColumn(stack1, 0);
        Grid.SetRowSpan(stack1, 2);
        LayoutGrid.Children.Add(stack1);

        // region 2 - top right
        var stack2 = new StackPanel
        {
            Background = new SolidColorBrush(Colors.Green)
        };
        Grid.SetColumn(stack2, 1);
        LayoutGrid.Children.Add(stack2);

        // region 3 - bottom right
        var stack3 = new StackPanel
        {
            Background = new SolidColorBrush(Colors.Blue)
        };
        Grid.SetColumn(stack3, 1);
        Grid.SetRow(stack3, 1);
        LayoutGrid.Children.Add(stack3);

        return LayoutGrid;
    }

的Xaml:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <StackPanel Background="Red" Grid.RowSpan="2"></StackPanel>
    <StackPanel Background="Blue" Grid.Column="1"></StackPanel>
    <StackPanel Background="Green" Grid.Column="1" Grid.Row="1"></StackPanel>
</Grid>