Generate the layout (XAML) by program

advertisements

How can I generate layout (XAML) programmatically?

Let say I have some kind of loop. And after each I want to generate this with the values I got:

                <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>


To add a new row to the grid, you will need to add a new row definition and then add the new controls. It will be similiar to the following logic:

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);

You will need to put the properties that you want to set where I have the comment and also provided the correct row number (zero based).

To add the entire thing...

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

And that's it. You'll just need to fill in the properties I haven't provided. Remember that your variable parentControl will be different. You haven't provided what control you are adding these into, so it is unclear what that would be.