1

如何以编程方式生成布局 (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>
4

2 回答 2

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

您需要将要设置的属性放在我有评论的地方,并提供正确的行号(从零开始)。

要添加整个内容...

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

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

于 2012-05-09T13:49:51.777 回答
2

一种选择是按照建议将所有代码作为Hexxagonal放置在代码隐藏中。

另一种更传统的选择是使用ItemsControl。这将通过将可视布局保留在 XAML 中而不是代码隐藏来实现更清晰的职责分离。

于 2012-05-09T13:57:16.993 回答