.net – WPF Localization in XAML, what is the simple, easy and elegant way of doing it

localizationnetwpfxaml

I have a very common question. What is the best way to do localization in a WPF app.
Well, I searched in SO and Binged a lot too. But I could not find any pointers which is really simple and elegant.

Assume that I have to display in UI something like:

In English: Orgnanization – Beoing

In French: Organizzazione – Beoing

    <StackPanel Orientation="Horizontal">
        <TextBlock Text="Organization -"></TextBlock>
        <TextBlock Text="{Binding Path=OrganizationName}">
        </TextBlock>
    </StackPanel>

Basically, I need to assign the localized text to Organization Label TextBlock.
Should I separate the hyphen from "Organization -" and put it in a separate label?

How do I do that?

Best Answer

Create a project WpfApplication1

Create a folder 'Localization'

Add a resource file (Strings.resx) in 'localization\' and add the string 'OrganizationText' and value 'Organisation'

When you compile, a designer.cs file is generated. Unfortunatly, all methods in this file are internal and we need public acces to enable string references from wpf. To do that, replace the .resx 'custom tool' with 'PublicResXFileCodeGenerator' (>=vs2008) and build again. Use this xaml in MainWindow.xaml:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:localization="clr-namespace:WpfApplication1.Localization"
        Title="MainWindow" Height="350" Width="525">
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="{x:Static localization:Strings.OrganizationText}"/>
        </StackPanel>
</Window>

To add the ' - ', you must use multibinding (see here)