accessing a resource dictionary in code wpf

微笑、不失礼 提交于 2019-12-05 11:09:31

问题


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



来源:https://stackoverflow.com/questions/3553329/accessing-a-resource-dictionary-in-code-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!