【发布时间】:2021-01-18 12:00:24
【问题描述】:
我正在构建一个 UWF 程序,我想让它每 x 秒 3 个随机方块改变颜色。
总共有大约 40 个方格,每个方格都命名为 rec1 - rec42。所以我的想法是通过组合两个字符串“rec”和一个随机整数来随机选择一个正方形。但是现在我必须从一个字符串中设置一个字段,这甚至可能吗?我什至理解/接近这一点吗?
这是我目前的方法
void animatedGraphics_Tick(object sender, object e) {
//List of color
String[] possibleColor = { "#FF443806", "#FF332E04", "#FF130F03" };
Random rnd = new Random();
//Loop for three square
for (int i = 0; i < 3; i++)
{
//generate pick squares to change
string square = ("rec" + rnd.Next(1, 43));
//Something like square.fill = possibleColor[rnd.Next(0,3)];
}
}
谢谢
编辑:这就是我最终使用的
void animatedGraphics_Tick(object sender, object e)
{
//List of color converted to from ARGB values
Color[] possibleColor = { Color.FromArgb(255, 65, 54 ,9),
Color.FromArgb(255, 19, 15, 3), Color.FromArgb(255, 51, 46, 3) };
Random rnd = new Random();
//Loop for three square
for (int i = 0; i < 3; i++)
{
//Use FindName to locate the shape
Rectangle square = (Rectangle) this.FindName("rec" + rnd.Next(1,42));
//Change the shape color
square.Fill = new SolidColorBrush(possibleColor[rnd.Next(0,3)]);
}
}
【问题讨论】:
-
正方形的确切类型是什么?
-
XAML 矩形 class===>
-
我建议将您的方块放在某种列表或数组中,而不是通过名称访问随机索引而不是对象,这将使您的代码更好地服务