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元素。 –