Introduction
There are many different kinds of resource paths used in WPF, I list almost all of them for our developer reference.
Background
This tip gives a reference to the developer about how to use resource path in WPF development.
Code in XAML File
- Reference resources that are in the current project (note: xxxx.png's 'build action' should set to 'Resource' or 'Embedded Resource' in VS)
<ImageBrush ImageSource="/currentAssemblyName;component/subfoldername/xxxx.png"/>
- Reference resources that are in other project (note: xxxx.png's 'build action' should set to 'Resource' or 'Embedded Resource' in VS)
<ImageBrush ImageSource="pack://application:,,,/otherAssemblyName;component/subfolder/xxx.png"/>
- Reference resources that are under relative path (note: it's better to set xxx.png's 'copy to output directory' attribute to 'always copy' in VS)
<ImageBrush ImageSource="pack://siteoforigin:,,,./subfolder/xxx.png "/>
- Reference resources that are under the absolute path:
<ImageBrush ImageSource="C:\test\xxx.png"/>
- When using a pack path, if you see this error:
System.UriFormatException: Invalid URI: Invalid port specified
but you are sure the pack path is correct. That's because the 'path:// scheme' has not registered, there are two solutions:
- Instantiate a '
System.Windows.Application
' that will invoke the PackUriHelper
class.
if (!UriParser.IsKnownScheme("pack"))
{
new System.Windows.Application();
}
- Invoke '
System.IO.Packaging.PackUriHelper.UriSchemePack
' once.
string s = System.IO.Packaging.PackUriHelper.UriSchemePack;