我的问题是:是我读错了 MSDN 还是 MSDN 错了?我正在尝试通过相对 URI 引用图像资源。
标题为 Pack URIs in WPF 的 MSDN 页面明确指出:
“本地程序集子文件夹中的资源文件”=“/Subfolder/ResourceFile.xaml”
在表 2 中:标记中的相对 URI(此处 http://msdn.microsoft.com/en-gb/library/aa970069.aspx ).
因此,我在 Vs2010 (v10.0.40219.1 SP1Rel) 中创建了新的 WPF/.NET 4.0 项目进行测试。
Startup Project: TryUri
App.xaml
MainWindow.xaml
Custom Ctrl Project: TryUri.CCL
Icons/folder.png <-- Marked As Resource!
Views/TestUC.xaml
在 TestUC.xaml 中:
<Canvas>
<Border>
<Image Source="/Icons/folder.png" Height="Auto" Width="Auto" />
</Border>
</Canvas>
在 MainWindow.xaml 中:
// xmlns:uc="clr-namespace:TryUri.CCL.Views;assembly=TryUri.CCL"
<uc:TestUC />
结果:图像没有显示!!
当我将路径更改为“../Icons/folder.png”时它确实有效。
如果我将 Icons/folder.png 复制到 TryUri.CCL/Views/文件夹中,则“Icons/folder.png”有效。
但是,我永远无法像 MSDN 声明的那样在“/Icons/folder.png”中使用前导正斜杠。
最佳答案
作为单独程序集运行时,相对包 URI 必须以 ../
开头或没有前导反斜杠的原因是相对 URI 的使用方式,from MSDN (emphasis mine) :
Absolute vs. Relative Pack URIs
...
If a leading backslash is used, however, the relative pack URI reference is then considered relative to the root of the application.
因此,如果您希望图像保持相对于您引用的程序集,只需省略前导斜线或使用 ../
(如果在子文件夹中)。
请参阅下图,了解其在运行时的外观示例:
关于c# - Wpf 绝对与相对包 URI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7772163/