WPF 下遍历作为Resource嵌入在可执行程序中的图片的一点思考解决方案
WPF 下遍历作为Resource嵌入在可执行程序中的图片的一点思考
先介绍下实现的功能
做一个看图片的WPF小程序,由于图片是只有这些不会变化,就将他们的属性设置为Resource输出在EXE里面方便使用
由于初学WPF,什么都不懂,在论坛里有些朋友的帮助下,一步步走过来,在这里讲下我实现的办法
读取嵌入的资源方法
但是这样必须知道每个图片的名字并且依次输入路径(在图片的名字不规则情况下)
把嵌入的资源“登记”到资源字典
读取资源字典中的所有项
然后foreach这个rd就可以得到所有“登记”了的图片的相对路径
完整的代码
MineDictionary.xaml 中的代码
初学乍道的,渣排版,烂代码,不过在网上找了不少资料都找不到实现的方法
放出来抛砖引玉一下,希望能有好的意见大家探讨
------解决方案--------------------
先介绍下实现的功能
做一个看图片的WPF小程序,由于图片是只有这些不会变化,就将他们的属性设置为Resource输出在EXE里面方便使用
由于初学WPF,什么都不懂,在论坛里有些朋友的帮助下,一步步走过来,在这里讲下我实现的办法
读取嵌入的资源方法
- C# code
Image.Source = new BitmapImage(new Uri(strRelativeUri, UriKind.Relative);
但是这样必须知道每个图片的名字并且依次输入路径(在图片的名字不规则情况下)
把嵌入的资源“登记”到资源字典
- XML code
<Image x:Key="Grid_Arrow" Source="/MineRecipes;component/Imgs/Grid_Arrow.png"/>
读取资源字典中的所有项
- C# code
ResourceDictionary rd = (ResourceDictionary)Application.LoadComponent(new Uri("MineDictionary.xaml", UriKind.Relative));
然后foreach这个rd就可以得到所有“登记”了的图片的相对路径
完整的代码
- C# code
ResourceDictionary rd = (ResourceDictionary)Application.LoadComponent(new Uri("MineDictionary.xaml", UriKind.Relative)); foreach (var v in rd.Keys) { //获取资源字典关键字 } foreach (DictionaryEntry v in rd) { //获取资源字典的source img1.Source = (v.Value as Image).Source; }
MineDictionary.xaml 中的代码
- XML code
<ResourceDictionary x:Class="MineRecipes.MineDictionary" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Image x:Key="Grid_Arrow" Source="/MineRecipes;component/Imgs/Grid_Arrow.png"/> <Image x:Key="Grid_Bed" Source="/MineRecipes;component/Imgs/Grid_Bed.png"/> <Image x:Key="Grid_Black_Wool" Source="/MineRecipes;component/Imgs/Grid_Black_Wool.png"/> <Image x:Key="Grid_Blaze_Powder" Source="/MineRecipes;component/Imgs/Grid_Blaze_Powder.png"/> <Image x:Key="Grid_Blaze_Rod" Source="/MineRecipes;component/Imgs/Grid_Blaze_Rod.png"/> <Image x:Key="Grid_Blue_Wool" Source="/MineRecipes;component/Imgs/Grid_Blue_Wool.png"/> 等等.....我有200多条,是写了个小程序生成的这些
初学乍道的,渣排版,烂代码,不过在网上找了不少资料都找不到实现的方法
放出来抛砖引玉一下,希望能有好的意见大家探讨
------解决方案--------------------
- C# code
string resourceName = this.GetType().Assembly.GetName().Name + ".g"; ResourceManager mgr = new ResourceManager(resourceName, this.GetType().Assembly); using (ResourceSet set = mgr.GetResourceSet(CultureInfo.CurrentCulture, true, true)) { foreach (DictionaryEntry each in set) { if (".jpg" == Path.GetExtension(each.Key.ToString()).ToLower()) { // 得到所有jpg格式的图片 } } }