在代码 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") };
我在另一个测试装置中得到的错误是 System.UriFormatException : Invalid URI: Invalid port specified.
The error I get in the other test fixture is System.UriFormatException : Invalid URI: Invalid port specified.
uri 字符串也适用于 xaml.有没有更好的方法在代码中加载资源字典?
The uri string also works in xaml. Is there a better way to load a resource dictionary in code?
干杯,
贝瑞尔
=== 更新 ===
正如我在这篇帖子中发现的那样,发生无效端口,因为包方案未注册,可以使用如下代码完成:
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);
我猜测,能够无误地加载带有包方案的字典的测试装置是因为 SUT 是那里的用户控件,并且在创建用户控件的实例时以某种方式加载资源.
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.
推荐答案
我使用的是 UriKind like
What I use is with UriKind like
var resource = new ResourceDictionary
{
Source = new Uri("/myAssemblyName;component/Themes/generic.xaml",
UriKind.RelativeOrAbsolute)
};
HTH
这篇关于在代码 wpf 中访问资源字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!