简体   繁体   中英

How to to use the same code in Win Store App and WP8 App to load string resource?

I have a Windows Phone 8 App, which I am now porting to Windows Store. Much of the WP8 code can be used in the Windows Store App without any changes. However, there is a problem with using the Resource Strings.

In the WP8 project the Strings are stored in .resx files and can be used in code through a generic class AppResources:

String msg = AppResources.MyMessageStringID;

In the WinStore project the Strings are stored in .resw files and can be used in code through a ResourceLoader:

public class StringLoader {
    private static ResourceLoader resourceLoader = new ResourceLoader();

    public static String Get(String stringName) {
        return resourceLoader.GetString(stringName);
    }
}

String msg = StringLoader.Get("MyMessageStringID");

I am looking for a way to use the same code to load the strings in both projects. My first approach was to use a compiler switch:

String msg = #if NETFX_CORE StringLoader.Get("MyMessageStringID"); #else AppResources.MyMessageStringID; #endif

Problem: The compiler switch cannot be used inline. It would have to be like this:

#if NETFX_CORE
    String msg = StringLoader.Get("MyMessageStringID"); 
#else 
    String msg = AppResources.MyMessageStringID; 
#endif

While this is possible for this simple example it would create a lot of redundant code in the real projects.

Of course I could create a "AppResources" class for Win Store as well:

public class AppResources{
    private static ResourceLoader resourceLoader = new ResourceLoader();

    public static String MyMessageStringID {
        get { return resourceLoader.GetString("MyMessageStringID "); }
    }
}

Such a class is created in WP8 automatically and (as far as I know) I would have to create it manually for the Windows Store App. Since there are several hundred strings in the Projects this would very, very much work.

Is there any nice, simple and clean solution to use the same code for localization in WP8 and Windows Store?

Exactly this problem solves my article how to share resources between Windows Phone and Windows 8 app .
In short, create Portable Class Library , put the resources there and reference this project in both apps, done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM