c# - Wpf 绝对与相对包 URI

标签 c# .net wpf windows

我的问题是:是我读错了 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.

因此,如果您希望图像保持相对于您引用的程序集,只需省略前导斜线或使用 ../(如果在子文件夹中)。

请参阅下图,了解其在运行时的外观示例:

Absolute vs. Relative Pack URIs

关于c# - Wpf 绝对与相对包 URI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7772163/

相关文章:

.net - 如何在配置文件中注册自定义 Log4Net 对象渲染器

WPF/MVVM - ItemsControl 中的 WrapPanel,添加子项上的动画

c# - RSA:如何在 java 中生成私钥并在 C# 中使用它?

c# - '=' 运算符后缺少操作数

c# - 重写属性上的 .net XmlSerializer

c# - 在 WPF 中为 ToggleButton OnMouseOver 的文本添加下划线

c# - 单个绑定(bind)的多个验证规则

c# - 返回之前等待异步函数

c# - 用于 Basecamp API 的 DotNetOpenAuth OAuth2

c# - 契约(Contract)优先的 WCF 服务 - 仍然有效吗?