【问题标题】:C# Setting a field from a stringC# 从字符串中设置字段
【发布时间】: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)]);
        }
    }

【问题讨论】:

标签: c# wpf


【解决方案1】:

可能不是最好的方法,但你可以通过他的名字调用 this.FindName()
然后Fill方法以Brush为参数,可以使用SolidBrushColor。
最后要从六进制转换为颜色,您可以使用 ColorConverter.ConvertFromString()

Color color = (Color)ColorConverter.ConvertFromString(possibleColor[rnd.Next(0,3)]);  
SolidColorBrush myBrush = new SolidColorBrush(color);  
Rectangle myRectangle = (Rectangle) this.FindName(square);  
myRectangle.Fill(myBrush);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-28
    • 1970-01-01
    • 1970-01-01
    • 2015-10-12
    • 1970-01-01
    • 2011-05-28
    • 2013-02-10
    • 1970-01-01
    相关资源
    最近更新 更多