How to use Resources.resw in Class library project in UWP?

2

I am currently working on Windows 10 UWP. At first, I only had one project to which I added a Constants.resw file to use resources which I saved in local storage and accessed them later. Now I have created a Background Task of type Timer and I want to access my database in Timer Background Task project so I created a Class Library Project and added all the POJOS and Utils classes in that project. Can someone suggest whether I can add a Constants.resw in class library project and how?

Also, I want to access it using below code which I used when I had a single project(Windows 10 UWP Project)

ApplicationDataContainer userSettings = ApplicationData.Current.LocalSettings;
if (!userSettings.Containers.ContainsKey(Constants.DB_AVAILABLE)) //if (!checkIfDBExists().Result)
{
     //some operations
}

When, I try to use Constants.resw in my background tasks, I get following error

Exception thrown: 'System.TypeInitializationException' in Common.dll
System.TypeInitializationException: The type initializer for 'Common.CommonResources.Constants' threw an exception. ---> System.Exception: Catastrophic failure (Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED))
at Windows.UI.Xaml.Application.get_Current()
at Common.CommonResources.Constants..cctor()
--- End of inner exception stack trace ---
at Common.CommonResources.Constants.get_DB_AVAILABLE()
at Common.DatabaseManager.getSQLiteConnection()
at Common.DatabaseManager.getLocationDetails()The type initializer for 'Common.CommonResources.Constants' threw an exception.
c#
windows-10-universal
asked on Stack Overflow Apr 25, 2016 by Kinjan Bhavsar • edited May 2, 2016 by Kinjan Bhavsar

1 Answer

2

You don't need to add a Resources.resw file to your Class Libraries or Windows Runtime Components because resources works at app level not at project level. This means your resources in your main app project can be "seen" and used across all your projects in your app. This is an example of how you can load resources externally:

ResourceContext resourceContext = ResourceContext.GetForViewIndependentUse();
ResourceMap resourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("Resources");

// Here you load the resource you need
var resourceValue = resourceMap.GetValue("resourceName", resourceContext);
answered on Stack Overflow Apr 25, 2016 by Tommaso Scalici

User contributions licensed under CC BY-SA 3.0