Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

WPF Resource Path Problem

0.00/5 (No votes)
4 Jan 2016 1  
Different resource paths using in WPF XAML file

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

  1. 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"/>
  2. 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"/>
  3. 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 "/>
  4. Reference resources that are under the absolute path:
    <ImageBrush ImageSource="C:\test\xxx.png"/>
  5. 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:
    1. Instantiate a 'System.Windows.Application' that will invoke the PackUriHelper class.
      if (!UriParser.IsKnownScheme("pack"))  
      { 
              new System.Windows.Application();  
      }
    2. Invoke 'System.IO.Packaging.PackUriHelper.UriSchemePack' once.
      string s = System.IO.Packaging.PackUriHelper.UriSchemePack;

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here