Change Resources Dynamically - Universal Windows Platform (UWP) Apps

INotifyPropertyChanged interface enables to change 2 or more resource (.resw) files dynamically in Universal Windows Platform (UWP) Apps.

Example

Resources.resw



Resources.de.resw


Implement INotifyPropertyChanged

In order to manage resources in one class, implement INotifyPropertyChanged class as like the following 2 classes, ResourceService and ResourceManager.

namespace MyApp
{
    using System.ComponentModel;
    using System.Runtime.CompilerServices;
    using Windows.ApplicationModel.Resources;

    public class ResourceService : INotifyPropertyChanged
    {
        #region Singleton Members
        private static readonly ResourceService _current = new ResourceService();

        public static ResourceService Current
        {
            get { return _current; }
        }
        #endregion

        #region INotifyPropertyChanged Members
        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void RaisePropertyChanged([CallerMemberName] string propertyName = null)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion

        readonly ResourceManager _resourceManager = new ResourceManager();

        public ResourceManager ResourceManager
        {
            get { return _resourceManager; }
        }

        public void ChangeCulture(string name)
        {
            ResourceManager.ResourceLoader = ResourceLoader.GetForCurrentView(string.Concat("Resources.", name));
            this.RaisePropertyChanged("ResourceManager");
        }
    }

    public class ResourceManager
    {
        private ResourceLoader _resourceLoader = ResourceLoader.GetForCurrentView();

        public ResourceLoader ResourceLoader
        {
            get { return _resourceLoader; }
            set { _resourceLoader = value; }
        }
        public string HelloWorld
        {
            get { return ResourceLoader.GetString("HelloWorld"); }
        }
    }
}

Binding

Bind properties of ResourceManager in XAML file like this:

MainPage.xaml.cs

public MainPage()
{
    InitializeComponent();
    this.DataContext = ResourceService.Current;
}
MainPage.xaml
<TextBox x:Name="textBox" Text="{Binding Path=ResourceManager.HelloWorld, Mode=OneWay}" />

Switch Hello World!

Now the text can be changed dynamically by calling ResourceService.ChangeCulture method:

Before:


MainPage.xaml.cs

private void button_Click(object sender, RoutedEventArgs e)
{
    ResourceService.Current.ChangeCulture("de");
}

After: