1
我在C#中有以下代码。我想随机突出显示九个图像中的一个的功能。代码如下所示,动态随机调用图像元素从C#到XAML#
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。所以请耐心等待。
强烈建议您使用'ItemsControl'而不是像这样在过程代码中手动操作UI元素。 –