accessing a resource dictionary in code wpf

2019-04-04 00:44发布

问题:

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?

Cheers,
Berryl

=== 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.

回答1:

What I use is with UriKind like

var resource = new ResourceDictionary
{
    Source = new Uri("/myAssemblyName;component/Themes/generic.xaml",
                     UriKind.RelativeOrAbsolute)
};

HTH



回答2:

@Prince Ashitaka answer tells you how to correct your URI

However the preferred way of accessing a ResourceDictionary is that in XAML you add it on as a merged dictionary

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="ImageResources.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

then you can access it via code using the TryFindResource(string Key) from any code behind file