如何将图像从资源文件夹添加到字典

问题描述:

好吧,我创建了一个dictionary,它包含一个字符串和一个对应的bitmap图像。我已将所有相关图像正确添加到项目资源中,并尝试了几种不同的方法将它们添加到运行时的dictionary中,以便根据输入的字母更容易地访问图像。这是我的代码,用于创建dictionary,并尝试从我的资源中填充它。如何将图像从资源文件夹添加到字典

Dictionary<String,Image> namesAndImages = new Dictionary<String, Image>(); 

var resources = Properties.Resources.ResourceManager.GetResourceSet(CultureInfo.CurrentCulture, true, true); 

foreach (System.Collections.DictionaryEntry myResource in resources) 
{ 
    if (myResource.Value is Bitmap) //is this resource is associated with an image 
    { 
     String resName = myResource.Key.ToString(); //get resource's name 
     Image resImage = myResource.Value as Image; //get the Image itself 

     namesAndImages.Add(resName, resImage); 
    } 
} 

它似乎无论出于何种原因并没有任何图像添加到字典中。我已经测试了几个不同的键值对,并且根本没有任何关键值对。任何想法的人?

+0

使用VS2017我可以再补充一个名为'Resource1'一个资源文件并添加一个名为'Image1'图像,然后访问它'Resource1.Image1',这是一个' Bitmap'。这个选项不适用于你吗? –

+0

即时通讯使用VS2012及其“资源”,但只有近40个图像,并且由于它们的大小而需要大量时间单独加载它们,这就是为什么我想使用“foreach”循环自动完成它的原因。 –

您可以使用<Resource file name>.ResourceManager获取与给定资源文件关联的ResourceManager。这些图像可以像这样访问:

Dictionary<string, Image> dict = new Dictionary<string, Image>(); 
var resourceManager = Resource1.ResourceManager; 
var resources = resourceManager.GetResourceSet(CultureInfo.CurrentCulture, true, true); 
foreach (DictionaryEntry item in resources) 
{ 
    if (item.Value is Bitmap) 
    { 
     dict.Add(item.Key as string, item.Value as Image); 
    } 
} 
+0

谢谢Tamás我现在会看看,看看这是否解决了问题并让你知道。欢呼声 –

+1

这是完美的Tamás。现在似乎正在用适当的图像和文本填充字典。非常感激。 –