WPF 下遍历作为Resource嵌入在可执行程序中的图片的一点思考
先介绍下实现的功能
做一个看图片的WPF小程序,由于图片是只有这些不会变化,就将他们的属性设置为Resource输出在EXE里面方便使用
由于初学WPF,什么都不懂,在论坛里有些朋友的帮助下,一步步走过来,在这里讲下我实现的办法
读取嵌入的资源方法
Image.Source = new BitmapImage(new Uri(strRelativeUri, UriKind.Relative);
<Image x:Key="Grid_Arrow" Source="/MineRecipes;component/Imgs/Grid_Arrow.png"/>
ResourceDictionary rd = (ResourceDictionary)Application.LoadComponent(new Uri("MineDictionary.xaml", UriKind.Relative));
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; }
<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多条,是写了个小程序生成的这些
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格式的图片 } }}