Wpf – accessing a resource dictionary in code wpf


The same line of code in the same assembly works for one test fixture but not another. Here is the line of code:

var dic = new ResourceDictionary { Source = new Uri("pack://application:,,,/MyApp.Wpf;component/ImageResources.xaml") };

The error I get in the other test fixture is System.UriFormatException : Invalid URI: Invalid port specified.

The uri string also works in xaml. Is there a better way to load a resource dictionary in code?


=== UPDATE ===

As I found in this posting, an Invalid port was occurring because the pack scheme wasn't registered, which can be done with code like so:

if (!UriParser.IsKnownScheme("pack"))
     UriParser.Register(new GenericUriParser(GenericUriParserOptions.GenericAuthority), "pack", -1);

I am guessing that the test fixture that was able to load the dictionary with the pack scheme without error is because the SUT is a user control there, and is somehow loading resources when an instance of the user control is created.

Best Solution

What I use is with UriKind like

var resource = new ResourceDictionary
    Source = new Uri("/myAssemblyName;component/Themes/generic.xaml",


Related Question