开发者

How do I get a resources/Resources.xaml from the executing assembly?

I have a ResourceDictionary in resource/Resources.xaml. However, I don't know ahead of time what the name of the .dll will be. Is there anyway to generate the uri for the ResourceDictionary on the fly? Originally, it was loaded using

var myResourceDictionary = new ResourceDictionary();
var uri = new Uri("/xxx;component/resource/Resources.xaml", UriKind.Relative);
myResourceDictionary.Source = uri;
Application.Current.Resources.MergedDictionaries.Add(myResourceDictionary);

where xxx could change to yyy if I include the file in a different Project.

Update. By turning the Resource.xaml from a Page to an Embedded Dictionary, I was able to load it using

// 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.GetManifestReso开发者_如何学JAVAurceNames())
{
    if (key.ToLower().EndsWith(".resources.xaml"))
    {
        Stream resource = assembly.GetManifestResourceStream(key);
        ResourceDictionary dict = XamlReader.Load(resource) as ResourceDictionary;
        Application.Current.Resources.MergedDictionaries.Add(dict);
    }
}

But this is a bit unsatisfactory. Still would be interested to know if there is a way to keep it as a Page and load it.


You should be able to build up the URI based on the current assembly. So using Jan-Peter's tip, an example would be:

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);

but you may need to use the long form:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜