この基本コードをすばやくまとめて、うまくいけば正しい軌道に乗ります。コードは一度呼び出すだけでよいので、Window_Loadedや他の同様の高レベルのコンテナに置く必要があります。潜在的には、LINQを使用してリストをフィルタリングするなどの他の処理を行うことができます(たとえば、画像コントロールを選択するとソースが無効になります)。ご質問がある場合はお知らせください。
private void Window_Loaded(object sender, RoutedEventArgs e)
{
//Set up lists to track which images/image controls have been used .. image resources and image controls will be removed from the relevant list once used.
int imageCount = 4;
IList<string> imageNames = new List<string>(imageCount) { "Image0", "Image1", "Image2", "Image3" };
IList<Image> imageControls = new List<Image>(imageCount) { img1, img2, img3, img4 };
//Pick an image resource at random to use as the one that will appear twice.
Random random = new Random();
int duplicatedImageIndex = random.Next(0, imageCount - 1);
Uri duplicatedImageUri = new Uri("/rnd_pic;component/Images/" + imageNames[duplicatedImageIndex] + ".jpg", UriKind.RelativeOrAbsolute);
//Select a random image control for first instance of image resource to be duplicated, then remove control from list to ensure it's not re-used.
int firstDuplicatedImageControlIndex = random.Next(0, imageCount - 1);
imageControls[firstDuplicatedImageControlIndex].Source = new BitmapImage(duplicatedImageUri);
imageControls.RemoveAt(firstDuplicatedImageControlIndex);
//Select a random image control for second instance of image resource to be duplicated, then remove control & image resource from relevant list to ensure they're not re-used.
int secondDuplicatedImageControlIndex = random.Next(0, --imageCount - 1);
imageControls[secondDuplicatedImageControlIndex].Source = new BitmapImage(duplicatedImageUri);
imageControls.RemoveAt(secondDuplicatedImageControlIndex);
imageNames.RemoveAt(duplicatedImageIndex);
//loop through remaining image controls setting one of the remaining random images, removing control & image resource from relevant list as you go.
while (imageControls.Any())
{
int randomUpperBound = --imageCount - 1;
int nextRandomImageIndex = random.Next(0, randomUpperBound);
int imageControlIndex = random.Next(0, randomUpperBound);
Uri nextImageUri = new Uri("/rnd_pic;component/Images/" + imageNames[nextRandomImageIndex] + ".jpg", UriKind.RelativeOrAbsolute);
imageControls[imageControlIndex].Source = new BitmapImage(nextImageUri);
imageControls.RemoveAt(imageControlIndex);
imageNames.RemoveAt(nextRandomImageIndex);
}
}
なぜ生命を困難にし、異なる画像を持つ2つの画像が同じ画像を持つのですか? –
はい、私は同じ画像で2つの画像の名前を同じように設定できますが、例えば 'img1'は常に' bitImages [0] 'を持ち、最後の3つの画像(' img2'、 'img3 '、' img4')は 'img1'と同じ画像を持っています – KinectUser
しかし、なぜ同じ画像を複数回保存していますか?なぜ元のものを参照して頭痛を救うのはなぜですか?それは1を取って数回だけ印刷するのではなく、同じ木を5回撮るのと同じです。 –