我有一个字符串imgchng
和二十个图片,image1, image2, image3,
等。
imgchng的值始终是其中一个图像的名称。
如何设置imgchng
所指的当前图像的值?
For例如,用户将imgchng
的值设置为image12
。我如何告诉image12
的来源改变?
imgchng.Source = (source goes here);
不起作用,因为那会设置字符串的属性,而不是图像。
我知道如何设置图像的来源,只是不是如何设置字符串所引用的任何图像的来源。
我的目的是避免长度超过1000行的大量if
语句,如下面的示例所示: / p>
if (textBlock2.Text == "First User Selection")
{
if (imgchng == "image1")
{
BitmapImage bmp = new BitmapImage(new Uri("/Images/FirstImg.png"));
image1.Source = bmp;
}
else if (imgchng == "image2")
{
BitmapImage bmp = new BitmapImage(new Uri("/Images/FirstImg.png"));
image2.Source = bmp;
}
//Continue this for all 20 images
}
else if (textBlock2.Text == "Second User Selection")
{
if (imgchng == "image1")
{
BitmapImage bmp = new BitmapImage(new Uri("/Images/SecondImg.png"));
image1.Source = bmp;
}
else if (imgchng == "image2")
{
BitmapImage bmp = new BitmapImage(new Uri("/Images/SecondImg.png"));
image2.Source = bmp;
}
//Continue this for all 20 images
}
else if (textBlock2.Text == "Third User Selection")
{
if (imgchng == "image1")
{
BitmapImage bmp = new BitmapImage(new Uri("/Images/ThirdImg.png"));
image1.Source = bmp;
}
else if (imgchng == "image2")
{
BitmapImage bmp = new BitmapImage(new Uri("/Images/ThirdImg.png"));
image2.Source = bmp;
}
//Continue this for all 20 images
}
else if (textBlock2.Text == "Fourth User Selection")
{
if (imgchng == "image1")
{
BitmapImage bmp = new BitmapImage(new Uri("/Images/FourthImg.png"));
image1.Source = bmp;
}
else if (imgchng == "image2")
{
BitmapImage bmp = new BitmapImage(new Uri("/Images/FourthImg.png"));
image2.Source = bmp;
}
//Continue this for all 20 images
}
基本上我正在尝试做的是,正如@ctacke所说,给定字符串'image1',我如何获得名为'image1'的控件实例?
答案 0 :(得分:2)
声明一个包含20个图像的BitmapImage数组。将其绑定到UI。将用户选择作为整数。使用索引从数组访问图像(显然是用户输入-1)。更改该图像的来源。这会解决您的问题吗?
答案 1 :(得分:-1)
要设置图像的来源,您必须执行以下操作。
BitmapImage bmp=new BitmapImage(new Uri("your image name will go here"));
image.Source=bmp;