Click here to Skip to main content
15,885,133 members
Articles / Desktop Programming / WPF
Tip/Trick

WPF Resource Path Problem

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
4 Jan 2016CPOL 16.6K   3  
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)
    XML
    <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)
    XML
    <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)
    XML
    <ImageBrush ImageSource="pack://siteoforigin:,,,./subfolder/xxx.png "/>
  4. Reference resources that are under the absolute path:
    XML
    <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.
      C#
      if (!UriParser.IsKnownScheme("pack"))  
      { 
              new System.Windows.Application();  
      }
    2. Invoke 'System.IO.Packaging.PackUriHelper.UriSchemePack' once.
      C#
      string s = System.IO.Packaging.PackUriHelper.UriSchemePack;

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
China China
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --