My question is: Am I reading MSDN wrong OR is MSDN wrong? I am trying to ref开发者_如何学Goerence an image Resource via relative URI.
The MSDN page titled Pack URIs in WPF clearly states that:
"Resource file in subfolder of local assembly" = "/Subfolder/ResourceFile.xaml"
in Table 2: Relative URIs in Markup (here http://msdn.microsoft.com/en-gb/library/aa970069.aspx ).
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
In TestUC.xaml:
<Canvas>
<Border>
<Image Source="/Icons/folder.png" Height="Auto" Width="Auto" />
</Border>
</Canvas>
In MainWindow.xaml:
// xmlns:uc="clr-namespace:TryUri.CCL.Views;assembly=TryUri.CCL"
<uc:TestUC />
Result: The image does not show up!!
When I change the path to "../Icons/folder.png" It does work.
If I copy the Icons/folder.png into the TryUri.CCL/Views/ folder, then "Icons/folder.png" works.
However, I can never get a leading forward slash to work as in "/Icons/folder.png" the way that MSDN states.
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):
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.
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:
The answer is this: The leading slash in a relative path always resolves to the main assembly, NOT the assembly that the markup is in.
To make it work the way that MSDN states, I would have to store all icons in an "Icons/" folder in the main assembly, instead of in the custom control dll.
If you choose to store the resources in the dll assembly in an "Icons/" folder, you must reference them with a path relative to the markup you're working on (i.e. "../Icons/folder.png
") OR you must qualify the path with the assembly name (i.e. "/AssemblyName;component/Icons/folder.png
")
Just replace < ApplicationName> with the name of your application and this should work
Source="/<ApplicationName>;component/Icons/folder.png"
精彩评论