WPF 下遍历作为Resource嵌入在可执行程序中的图片的一点思考

wly880601 2012-02-23 10:19:52
先介绍下实现的功能
做一个看图片的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));

然后foreach这个rd就可以得到所有“登记”了的图片的相对路径

完整的代码
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 中的代码
<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多条,是写了个小程序生成的这些


初学乍道的,渣排版,烂代码,不过在网上找了不少资料都找不到实现的方法
放出来抛砖引玉一下,希望能有好的意见大家探讨
...全文
222 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
wly880601 2012-02-25
  • 打赏
  • 举报
回复
to nonocast:

感谢你的热心回答,给了我很大的帮助
nonocast 2012-02-24
  • 打赏
  • 举报
回复

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格式的图片
}
}
}

详细见这里,http://nonocast.cn/?p=2562

110,499

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧