问题
Resource files in Silverlight can be accessed using the code below:
ResourceManager rm = new ResourceManager("MyLibraryNamespace.MyFolder.MyResources", Assembly.GetExecutingAssembly());
However in my application this piece of code is not in the application itself, but in a Silverlight class library and the app has reference to it; changing the namespace to the "MyAppNamespace" just generates error.
How can I reach the resources in the xap file from the Silverlight class library?
回答1:
There is a nice video here: http://msdn.microsoft.com/en-us/hh336287
The trick is to write a "proxy" class so that you can reference strings from XAML. From MSDN:
public class LocalizedStrings {
public LocalizedStrings() { }
private static sdkGlobalizationCS.AppResources localizedResources = new sdkGlobalizationCS.AppResources();
public sdkGlobalizationCS.AppResources LocalizedResources { get { return localizedResources; } }
}
And in XAML (after adding the class in the static resources):
<ListBoxItem Content="{Binding Path=LocalizedResources.LangRegionNameFrFR, Source={StaticResource LocalizedStrings}}" />
回答2:
This is good and I was able to do the same.
In my case I have the same library shared between applications so I extract dynamically the name of the assembly:
var ast = assembly.FullName;
char[] delimit = new char[] { ',' };
string[] parts = ast.Split(delimit);
var gResources = new System.Resources.ResourceManager(parts[0]+"resource path here", assembly);
回答3:
In order to achieve what I wanted I had to do the following:
var assembly = Application.Current.GetType().Assembly;
And after that I can create ResourceManager with the resources like this:
var rm = new System.Resources.ResourceManager(name, assembly);
where name is the path from my first post.
来源:https://stackoverflow.com/questions/8384851/access-resx-in-application-from-silverlight-class-library