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?
Localization is the translation of application resources into localized versions for the specific cultures that the application supports. When you localize in WPF, you use the APIs in the System.
One of the first things you will encounter while working with WPF is XAML. XAML stands for Extensible Application Markup Language. It's a simple and declarative language based on XML. In XAML, it very easy to create, initialize, and set properties of objects with hierarchical relations.
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)
I Bind all the labels, etc. in my application to an object that I use for displaying the different languages. I store all the strings in a database and just retrieve the proper strings based on the language the user has selected. This has the advantage of instantly updating during run-time. This way the user does not need to restart the application like you would if you chose to make the windows 'Localizable'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With