Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何从正在执行的程序集中获取resources/resources.xaml?_C#_Wpf - Fatal编程技术网

C# 如何从正在执行的程序集中获取resources/resources.xaml?

C# 如何从正在执行的程序集中获取resources/resources.xaml?,c#,wpf,C#,Wpf,我在resource/Resources.xaml中有一个ResourceDictionary。然而,我不知道提前什么名称的.dll的时间。是否仍然可以动态生成ResourceDictionary的uri?最初,它是使用 var myResourceDictionary = new ResourceDictionary(); var uri = new Uri("/xxx;component/resource/Resources.xaml", UriKind.Relative); myResou

我在resource/Resources.xaml中有一个ResourceDictionary。然而,我不知道提前什么名称的.dll的时间。是否仍然可以动态生成ResourceDictionary的uri?最初,它是使用

var myResourceDictionary = new ResourceDictionary();
var uri = new Uri("/xxx;component/resource/Resources.xaml", UriKind.Relative);
myResourceDictionary.Source = uri;
Application.Current.Resources.MergedDictionaries.Add(myResourceDictionary);
如果我将文件包含在另一个项目中,则xxx可以更改为yyy

更新。通过将Resource.xaml从页面转到嵌入式词典,我可以使用

// http://chris.59north.com/post/Storing-application-wide-styles-in-external-files-aka-The-ExternalStyleManager.aspx
Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
foreach (var key in assembly.GetManifestResourceNames())
{
    if (key.ToLower().EndsWith(".resources.xaml"))
    {
        Stream resource = assembly.GetManifestResourceStream(key);
        ResourceDictionary dict = XamlReader.Load(resource) as ResourceDictionary;
        Application.Current.Resources.MergedDictionaries.Add(dict);
    }
}

但这有点不令人满意。仍然有兴趣知道是否有方法将其保留为页面并加载。

您应该能够基于当前程序集构建URI。因此,使用Jan Peter的提示,一个例子是:

var myResourceDictionary = new ResourceDictionary();
var uriPath = string.Format("/{0};component/resource/Resources.xaml", 
    typeof(classInAssembly).Assembly.GetName().Name);
var uri = new Uri(uriPath, UriKind.RelativeOrAbsolute);
myResourceDictionary.Source = uri;
Application.Current.Resources.MergedDictionaries.Add(myResourceDictionary);
但您可能需要使用长格式:

var uriPath = string.Format("pack://application:,,,/{0};component/resource/Resources.xaml", 
    typeof(classInAssembly).Assembly.Name);

这不是对您问题的回答,但请记住,
Assembly.getExecutionGassembly
有时会给出错误的结果。更好的方法是使用
typeof(ClassinaAssembly)。Assembly
很好,感谢Jan-Peter的提醒。顺便说一句,我不需要长格式。@tofutim-URI有时可能会很挑剔,具体取决于您在何处以及如何使用它们。