在跟着网上一个视频做一个文件浏览器的时候,中途需要插入一些图片文件夹和文件的图标资源,做出像windows这样的效果:
在程序中加载资源:
//By defaul, we presume an image
var image = "images/file.png";
//If the name is blank, we presume it's a drive as we cannot have a blank file or folder name
if (string.IsNullOrEmpty(name))
image = "images/drive.png";
else if (new FileInfo(path).Attributes.HasFlag(FileAttributes.Directory))
image = "images/directory_close.png";
return new BitmapImage(new Uri($"/{image}"));
出现报错:
视频中的小哥说了:another kind of quirk to WPF……然后在Uri前面加上了"pack://application:,,,"
好像说是只有加上了这个路径,编译的时候才会把资源加载进application中,真的是quirk。改了之后成功编译并运行【😊】:
注意:前面xaml中加载资源也会出现这个问题,修改图片属性复制到输出目录改为始终复制,也可解决。