65.9K
CodeProject is changing. Read more.
Home

WPF Resource Path Problem

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1 vote)

Jan 4, 2016

CPOL
viewsIcon

17110

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;