以编程方式生成布局(XAML)
如何以编程方式生成布局(XAML)?以编程方式生成布局(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>
要添加一个新行到网格,你将需要添加一个新行定义,然后添加新的控件。这将是类同以下逻辑:
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
将有所不同。你没有提供你将这些添加到什么控制,所以它不清楚会是什么。
当我试图将网格添加到“parentControl”它说“该参数不正确。”并没有什么比修复错误更有价值...比你长的回答当然..也许我应该寻找ItemsControl instaed ..因为这对我来说太复杂了... –
好吧,1小时后我明白了。 ..我让你的代码适合我的项目。你是老板,besos! –
一种选择是将所有代码放在代码隐藏中作为Hexxagonal as suggested。
另一种选择和更传统的方法是使用ItemsControl。通过将可视化布局留在XAML中而不是代码隐藏,这将允许更清晰的职责分离。
是的。我应该提到他的编程方法不会是最好的。 – scottheckel
毫无疑问。我只是想在OP不知道ItemsControl的情况下将其抛出。 –
你想添加新的行或产生整个事情? – scottheckel
我想要根据需要生成整个事物...。 –
好的,看看我的答案。我更新它来添加一个网格。 – scottheckel