以编程方式生成布局(XAML)

Bad*_*ari 1 xaml windows-phone-7

如何以编程方式生成布局(XAML)?

假设我有某种循环.在每次之后,我想用我得到的值生成这个:

                <Grid Height="150" Name="grid1">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition />
                        <ColumnDefinition Width="200" />
                    </Grid.ColumnDefinitions>
                    <Image Height="150" Name="image1" Stretch="Fill" Width="200" Grid.Column="1" Source="/Ilm;component/Images/testicon.png" HorizontalAlignment="Right" VerticalAlignment="Top" />
                    <TextBlock Height="51" Name="textBlock1" Text="Paris" Margin="12,20,0,0" HorizontalAlignment="Left" VerticalAlignment="Top" FontSize="40" />
                    <TextBlock FontSize="40" Height="51" HorizontalAlignment="Left" Margin="13,75,0,0" Name="textBlock2" Text="19°C" VerticalAlignment="Top" />
                </Grid>
Run Code Online (Sandbox Code Playgroud)

sco*_*kel 5

要向网格添加新行,您需要添加新行定义,然后添加新控件.它将类似于以下逻辑:

rowNumber = 0; // Set the current row that you are adding 
grid1.RowDefinitions.Add(new RowDefinition());

Image img = new Image();
img.Height = 150;
img.Name = "image1";
img.Stretch = Stretch.Fill;
img.Width = 200;
img.HorizontalAlignment = HorizontalAlignment.Right;
img.VerticalAlignment = VerticalAlignment.Top;
// Set your image properties
img.SetValue(Grid.RowProperty, rowNumber);
img.SetValue(Grid.ColumnProperty, 1);
grid1.Children.Add(img);

TextBlock tb1 = new TextBlock();
// Set your text block properties
tb1.SetValue(Grid.RowProperty, rowNumber);
tb1.SetValue(Grid.ColumnProperty, 0);
grid1.Children.Add(tb1);

TextBlock tb2 = new TextBlock();
// Set your text block properties
tb2.SetValue(Grid.RowProperty, rowNumber);
tb2.SetValue(Grid.ColumnProperty, 0);
grid1.Children.Add(tb2);
Run Code Online (Sandbox Code Playgroud)

您需要将要设置的属性放在我有注释的位置,并提供正确的行号(基于零).

要添加整个东西......

Grid grid1 = new Grid();
grid1.Height = 150;
grid1.Name = "grid1";
parentControl.Children.Add(grid1); // Note: parentControl is whatever control you are added this to
grid1.ColumnDefinitions.Add(new ColumnDefinition());
grid1.ColumnDefinitions.Add(new ColumnDefinition { Width = 200});

// From here insert the code for adding a row that is provided above
Run Code Online (Sandbox Code Playgroud)

就是这样.你只需要填写我没有提供的属性.请记住,您的变量parentControl会有所不同.您还没有提供将这些控件添加到哪个控件中,因此不清楚它是什么.