在 UWP/Windows Store App 中使用全局 ResourceLoader

Using a global ResourceLoader in UWP/Windows Store App

我使用 resw 文件在我的应用程序中存储文字字符串,并使用

访问它们
(new Windows.ApplicationModel.Resources.ResourceLoader()).GetString("resourceName");

我觉得这有点麻烦,希望有一个全局资源加载器,例如在静态 class 中:

public static class ResourceLoader
{
    private static Windows.ApplicationModel.Resources.ResourceLoader loader = new Windows.ApplicationModel.Resources.ResourceLoader();

    public static string Get(string name)
    {
        return loader.GetString(name);
    }
}

这样一来,我只有一个 ResourceLoader 实例,而且很容易访问。有什么反对这样做的吗?它似乎在我的应用程序中有效,但我不想在这里错过任何东西。

使用全局 ResourceLoader 没有记录在案的缺点。 尽管您应该使用静态方法 GetForViewIndependentUse() 而不是构造函数来获取实例; 此方法为您提供了一个不依赖于任何特定上下文的 ResourceLoader 实例,因此您可以从代码中的任何位置检索应用程序中的资源。

我不知道它是否有帮助,但这是 class 我用代码从 ResW 加载字符串:

using System;
using System.Threading.Tasks;
using Windows.ApplicationModel.Resources;

namespace ProjectName.Services
{
    public sealed class ResourceService : ObservableObject
    {
        private ResourceService() {}

        public static Task<ResourceService> CreateServiceAsync ()
        {
            return Task.FromResult(new ResourceService());
        }

        public Task<string> GetResourceStringAsync (string stringname)
        {
            try
            {
                var resourceloader = ResourceLoader.GetForCurrentView();
                return Task.FromResult(resourceloader.GetString(stringname));
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        public Task<string> GetResourceStringAsync (string resource, string stringname)
        {
            try
            {
                var resourceloader = ResourceLoader.GetForCurrentView(resource);
                return Task.FromResult(resourceloader.GetString(stringname));
            }
            catch (Exception ex)
            {
                return null;
            }
        }
    }
}

我在 App.xaml.cs 的 OnLaunched 事件中初始化它:

this.ResourceService = await ResourceService.CreateServiceAsync()

然后食用它:

var stringtoget = await App.ResourceService.GetResourceStringAsync("resourcename", "stringkeyname");