问题描述
作为一个自学项目,我正在构建一个作为 WPF 应用程序的记忆游戏。
问题:是否有一种有效的方法可以将资源目录中的所有图像文件添加到 List<BitmapImage>
中,以便我可以轻松创建 x 数量图像的网格?
对我来说,理想的做法是将所有这些图像一次存储在一个列表中并在列表中循环以设置 (Image)pictureBox.source = myImageList[i]
这里的限制是 myImage.BeginInit()
方法只能被调用一次,而且不能覆盖 BitmapImage 的实例。 (“无法覆盖”是指一旦设置了 BitmapImage 就无法更改其保存的图片。
结论:我的资源文件夹中有很多图片。有没有比以下代码更好的方法来将我从该文件夹中的所有图像保存在列表中。 (因为这个方法需要我为每个我想添加到列表中的资源创建一个BitmapImage的实例。感觉效率低下)
BitmapImage myImage0 = new BitmapImage();
myImage0.BeginInit();
myImage0.UriSource = new Uri(@"/resources/ukflag.jpg",UriKind.Relative);
pictureBox.source = myImage0;
myImage0.EndInit();
myImageList.Add(myImage0);
解决方法
感谢评论,我找到了方法。 这是对我有用的代码(在将图片的构建操作设置为资源之后)
ResourceSet resourceSet = Properties.Resources.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture,true,true);
foreach (DictionaryEntry entry in resourceSet)
{
string resourceKey = entry.Key.ToString();
myImageList.Add(new BitmapImage(new Uri(@"pack://application:,/Resources/" + resourceKey + ".jpg")));
}