0

我在 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 个骰子。第二行和列+1的最后4个骰子。我使用 Dice1、Dice2、Dice3 等名称,因为我想稍后给每个标签一个随机整数。有人有想法吗?

for (int i = 0; i < 8; i++)
{
    Label Dice = new Label();
}
4

2 回答 2

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); 
}
于 2012-11-05T13:49:54.297 回答
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]);
}
于 2012-11-05T13:51:48.710 回答