Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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.

like image 424
Berryl Avatar asked Aug 24 '10 03:08

Berryl


People also ask

How do you use resource dictionary?

You can reference a resource throughout an app or from any XAML page within it. You can define your resources using a ResourceDictionary element from the Windows Runtime XAML. Then, you can reference your resources by using a StaticResource markup extension or ThemeResource markup extension.

What is resource dictionary in WPF?

In Extensible Application Markup Language (XAML), the ResourceDictionary class is typically an implicit collection element that is the object element value of several Resources properties, when given in property element syntax. For details on implicit collections in XAML, see XAML Syntax Terminology.

What all we can store in resource dictionary in WPF?

Adding a WPF Resource Dictionary Since WPF applications have rich media and graphics support, reusable styles need to be utilized and in a managed way. We can define the styles in WPF XAML files, or perhaps we can manage to accumulate all our useful styles for a particular application in a resource dictionary file.

What is a XAML resource dictionary?

A resource dictionary is a repository for XAML resources, such as styles, that your app uses. You define the resources in XAML and can then retrieve them in XAML using the {StaticResource} markup extension and {ThemeResource} markup extension s. You can also access resources with code, but that is less common.


1 Answers

What I use is with UriKind like

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

HTH

like image 137
Prince Ashitaka Avatar answered Nov 16 '22 00:11

Prince Ashitaka