从C#动态随机调用图像元素到XAML

时间:2014-02-26 12:14:29

标签: c# wpf xaml

我在C#中有以下代码。我想要随机突出显示九个图像中的一个的功能。代码如下,

    public void randomize(object sender, MouseButtonEventArgs e)
    {
        String img = "image";
        int random = RandomNumber(10, 18);    //Generate Random Number
        score.Content = random;             
        img += random;                      //append generated number to "image"

        //Call function to highlight behind image
        ToGold(random);
    }

我尝试使函数调用ToGold(random)能够动态引用XAML上的一个图像。但我无法按照我的意图使代码工作。所以我采取了如下的蛮力方法,

    public void ToGold(int Img)
    {
        Uri gold = new Uri("/Start;component/Images/gold1.png", UriKind.Relative);     //Set Uri path of gold image
        ImageSource ImgSrc = new BitmapImage(gold);                                    //Define ImageSource and assign

        switch(Img)
        {
            case 10:
                {
                    image10.Source = ImgSrc;
                    break;
                }
            case 11:
                {
                    image11.Source = ImgSrc;
                    break;
                }
            case 12:
                {
                    image12.Source = ImgSrc;
                    break;
                }
            case 13:
                {
                    image13.Source = ImgSrc;
                    break;
                }
            case 14:
                {
                    image14.Source = ImgSrc;
                    break;
                }
            case 15:
                {
                    image15.Source = ImgSrc;
                    break;
                }
            case 16:
                {
                    image16.Source = ImgSrc;
                    break;
                }
            case 17:
                {
                    image17.Source = ImgSrc;
                    break;
                }
            case 18:
                {
                    image18.Source = ImgSrc;
                    break;
                }
        }
    }

所以我的问题是如何通过使代码动态化来使代码高效?有人可以帮帮我吗?

注意:我刚开始学习WPF。所以请耐心等待。

1 个答案:

答案 0 :(得分:0)

您可以使用窗口上的FindName方法按名称查找元素 或者您可以按顺序创建一个包含图像的数组,即{ image0, image1, image2, image3, ... },然后使用随机索引访问该数组。