2016-07-03 47 views
0

在我的應用我想動態創建一個網格佈局,但沒有得到預期的輸出網格佈局:如何創建動態的XAML

下面是我試過的代碼:

 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

+0

的就是你得到的輸出? – derpirscher

+0

我只得到兩列,第1列沒有創建行。 – Dishant

+0

您未將Col1Grid添加到您的LayoutGrid中 – derpirscher

回答

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>