WPF绝对与相对的Pack URIWPF、Pack、URI

2023-09-03 02:05:17 作者:心上无人

我的问题是:难道我阅读MSDN错误的或者是MSDN错我试图通过相对URI来引用图像的资源的

My question is: Am I reading MSDN wrong OR is MSDN wrong? I am trying to reference an image Resource via relative URI.

在MSDN页标题为的Pack URI WPF 中明确指出:

The MSDN page titled Pack URIs in WPF clearly states that:

,在当地组装的子文件夹中的资源文件= 的 /Subfolder/ResourceFile.xaml

在表2中的标记相关的URI(这里 http://msdn.microsoft.com/en-gb/library/aa970069.aspx )。

in Table 2: Relative URIs in Markup (here http://msdn.microsoft.com/en-gb/library/aa970069.aspx ).

所以,我在VS2010(v10.0.40219.1 SP1Rel)创建新的WPF / .NET 4.0的项目进行测试。

So, I created new WPF/.NET 4.0 projects in Vs2010 (v10.0.40219.1 SP1Rel) to test.

Startup Project: TryUri
    App.xaml
    MainWindow.xaml
Custom Ctrl Project: TryUri.CCL
    Icons/folder.png <-- Marked As Resource!
    Views/TestUC.xaml

在TestUC.xaml:

In TestUC.xaml:

<Canvas>
    <Border>
        <Image Source="/Icons/folder.png" Height="Auto" Width="Auto" />
    </Border>
</Canvas>

在MainWindow.xaml:

In MainWindow.xaml:

// xmlns:uc="clr-namespace:TryUri.CCL.Views;assembly=TryUri.CCL"

<uc:TestUC />

结果:图片显示不出来!! 的

当我将路径更改为../Icons/folder.png它的工作。

When I change the path to "../Icons/folder.png" It does work.

如果我复制图标/ folder.png到TryUri.CCL /浏览/文件夹,然后选择图标/ folder.png的作品。

If I copy the Icons/folder.png into the TryUri.CCL/Views/ folder, then "Icons/folder.png" works.

不过,我从来没有领先斜线工作,成为/Icons/folder.png的方式,MSDN的状态。

However, I can never get a leading forward slash to work as in "/Icons/folder.png" the way that MSDN states.

推荐答案

究其原因,作为一个单独的程序运行的时候,你的相对包URI必须以 ../ 或没有领导反斜杠是因为相对URI如何使用,的

The reason, when running as a separate assembly, that your Relative Pack URI must begin with ../ or no leading backslash is because of how relative URIs are used, from MSDN (emphasis mine):

绝对与相对的Pack URI

...

如果一个前置反斜杠被使用,但是,相对包URI引用,则被视为相对于应用程序的根目录

If a leading backslash is used, however, the relative pack URI reference is then considered relative to the root of the application.

因此​​,如果你想将图像保持相对于你的引用程序集,只是省略了领先的斜线或​​使用 ../ 如果在一个子文件夹。

Therefore if you'd like the images to remain relative to your referenced assembly, simply omit the leading slash or use ../ if in a sub-folder.

请参阅下面的图片为如何着眼于运行时的一个例子:

See the image below for an example of how this looks at runtime: