Setting the value of an image using a String
I have a string, imgchng
, and twenty images, image1, image2, image3,
etc.
The value of imgchng is always the name of one of the images.
How would I set the value of the the current image that imgchng
is referring to?
For instance, the user sets the value of imgchng
as image12
. How would I tell image12
's source to change?
imgchng.Source = (source goes here);
doesn't work, because that would set the property of the string, not the image.
I know how to set the source of the image, just not how to set the source of whatever image the string is referring to.
My intention is to avoid a humongous if
statement that would be over 1000 lines long, like the example one below:
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 = bm开发者_JAVA百科p;
}
//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
}
Basically what I'm trying to do is, as @ctacke said, given the string 'image1', how do I get the instance of the control named 'image1'?
Declare a BitmapImage array of 20 images. Bind that to the UI. Take the user selection as an integer. Access the image from array using index (obviously user input -1).Change the source of that image. Does this resolve your problem?
To set the source of the image you have to do the following.
BitmapImage bmp=new BitmapImage(new Uri("your image name will go here"));
image.Source=bmp;
Hope this helps.
精彩评论