我在XAML中有以下代码,但我想以编程方式创建这些标签。
<Label Content="" Name="Dice1" HorizontalAlignment="Left" Margin="19,11,0,0" VerticalAlignment="Top" Grid.Column="0"/>
<Label Content="" Name="Dice2" HorizontalAlignment="Left" Margin="19,11,0,0" VerticalAlignment="Top" Grid.Column="1"/>
<Label Content="" Name="Dice3" HorizontalAlignment="Left" Margin="19,11,0,0" VerticalAlignment="Top" Grid.Column="2"/>
<Label Content="" Name="Dice4" HorizontalAlignment="Left" Margin="19,11,0,0" VerticalAlignment="Top" Grid.Column="3"/>
<Label Content="" Name="Dice5" HorizontalAlignment="Left" Margin="19,10,0,0" VerticalAlignment="Top" Grid.Row="1"/>
<Label Content="" Name="Dice6" HorizontalAlignment="Left" Margin="19,10,0,0" VerticalAlignment="Top" Grid.Row="1" Grid.Column="1"/>
<Label Content="" Name="Dice7" HorizontalAlignment="Left" Margin="19,10,0,0" VerticalAlignment="Top" Grid.Row="1" Grid.Column="2"/>
<Label Content="" Name="Dice8" HorizontalAlignment="Left" Margin="19,10,0,0" VerticalAlignment="Top" Grid.Row="1" Grid.Column="3"/>
我认为最好的方法是在for循环中?我想要在同一行和列+1上的前4个骰子。第二行的最后4个骰子和+1列。我正在使用名称Dice1,Dice2,Dice3,...因为我想稍后给每个标签一个随机整数。有人有想法吗?
for (int i = 0; i < 8; i++)
{
Label Dice = new Label();
}
答案 0 :(得分:1)
填写每个labal的属性,然后将其添加到您的父控件。在下面的示例中,我假设您使用的是名为myCanvas
的画布。
for (int i = 0; i < 8; i++)
{
Label Dice = new Label();
Dice.Name = "Dice" + (i + 1).ToString();
Dice.HorizontalAlignment = HorizontalAlignment.Left;
//fill the rest of the properties
//...
//you need to add the label to your parent control
myCanvas.Children.Add(Dice);
}
答案 1 :(得分:0)
这可能会让你开始。
Label[] labels = new Label[8];
for(int i = 0; i < 8; i++)
{
labels[i] = new Label();
labels[i].Text = new Random().NextInt(1, 8);
labels[i].DoOtherStuff();
parent.Controls.Add(labels[i]);
}