How to localize an WPF application with a resource files

I currently need to localize a WPF application that consists of a main application project as well as separate DLL projects that provides the app with general user controls, model classes etc.

Many of the tutorials I found suggested using the App.xaml file to localize the application. This does not work for me, since I need to be able to localize all parts of the application, as well as the separate DLLs.

Fortunately, it is really easy to get resource file-based localization up and running for your WPF app. Just follow the steps below…and keep in mind that the names that I use are only boring suggestions. You can go as wild as you want to when you try it out for yourself.

Step 1. Create a WPF application

First, create a new WPF application. I call mine…HelloWorld!

WPF app

An insanely complex application called “HelloWorld”

As you can see, I also added something to localize. I chose a Button; what do you choose? Tell me in the comments below 🙂

Step 2. Create the resource file

Now, let’s add a resource file into which we will add our textual content.

To separate resource files from the rest of the application, I place the file in a Resources folder and name it AppLanguage.resx.

Resource file

A resource file with (so far) one single parameter

Now, go ahead and add some content to the resource file. As you can see, I added a parameter called ButtonText, which I will apply to the Button.

In order to access the resource file from XAML, we also need to make the file public:

Make the resource file public

Make the resource file public

Once this is done, let’s access the resource file from XAML.

Step 3. Access the resource file content from XAML

Now, let’s use the resource file parameter in our XAML file.

Connect the XAML code to your context class by adding the following line into the Window tag:

xmlns:Resources="clr-namespace:HelloWorld.Resources"

After that, you can access the resource parameter as such:

<Button Content="{x:Static Resources:AppLanguage.Menu_LoadData_All}"></Button>

Voilá! The text is finally displayed within the button:

The resource text is displayed within the button.

Since we use a resource file instead of App.xaml, we can use the same resource file to translate textual content code-behind as well. Let’s try it out.

Step 4. Access the resource content file from code

To access resource file content from code, simply call the AppLanguage class as such:

using HelloWorld.Resources; //Add this topmost among the using directives
MessageBox.Show(AppLanguage.ButtonText);   //Add this code inside the MainWindow() ctor

When we now start our application, the message box is displayed….juuust the way we want it:

Resource file content

Advertisements