我在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);
}
}
但这有点令人不满意。仍然有兴趣知道是否有办法将其保存为页面并加载它。
答案 0 :(得分:2)
您应该能够根据当前程序集构建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);