Hunt3R
Hunt3R

Reputation: 117

How to pick a random image

I have recently started learning Windows phone app development with no c# knowledge, and I wanted to make an app that displays a random image on the ImageBox when the button is clicked.

How will I go about making a random image (from a list) come up every time the user presses the button?

Here is all I have so far:

myImage.Source = new BitmapImage(new Uri("/Images/Pic1.png", UriKind.Relative));

Upvotes: 0

Views: 5279

Answers (1)

McGarnagle
McGarnagle

Reputation: 102793

If you have a list of images, or an image naming convention, then this is easy.

For example, if your images are named "Pic1" through "Pic10", then just use:

const int numberOfImages = 10;
var rand = new Random();
int imageNumber = rand.Next(numberOfImages) + 1;
string imageName = string.Format("/Images/Pic{0}.png", imageNumber);
myImage.Source = new BitmapImage(new Uri(imageName, UriKind.Relative));

Or if you have an array with the names of available images:

string[] imageNames = { "Pic1.png", "AnotherPic.png" };
var rand = new Random();
string imageName = imageNames[rand.Next(imageNames.Length)];
string imageName = string.Concat("/Images/", imageName);
myImage.Source = new BitmapImage(new Uri(imageName, UriKind.Relative));

Edit

It is more tricky than you might think to enumerate "Resource" images at runtime. See here for a discussion of this topic.

Edit #2

Actually, one of the answers from the above link has a nifty approach -- use a T4 template to generate the list of images at compile time.

Upvotes: 4

Related Questions