Tutorial – Binding to Resources.resx for strings in a WPF Application: A technique to prepare for localization

Update: This is no longer a recommended way to do localization in WPF.
Use this project from NuGET: WPFSharp.Globalizer
Also read this post: How to change language at run-time in WPF with loadable Resource Dictionaries and DynamicResource Binding

Introduction

Ok, so if you are going to have a string visible in your WPF application and your application can be in multiple languages, you are facing the localization problem.

Usually people as themselves two questions:

  • Do I localize or not?
  • How do I localize?

The answers are usually not now and I don’t know. So no localization work is done at first. Later, you wish you were more prepared for localization.

Well, I am here to tell you that you can at least prepare to be localized by doing a few simple steps:

  1. Centralize your strings in a publicized Resources.resx file.
  2. Add a reference to your Properties.
  3. Replacing any statically entered text with the name of the string resource.
  4. Do you best to use dynamic sizing.

Preparing your strings for localization

If you are going to have a string in your WPF application, it is a good idea to store those strings in a centralized place for localization purposes. Usually in Visual Studio, that is in Resources.resx.

Cialis is an additional impotence problems treatment, http://www.horizonhealthcareinc.com/ which is gaining interest at a faster pace. The reason for more popular at a faster pace is because of its effectiveness.

Often a string is entered directly into an the WPF XAML. This is not recommended. Maybe you are thinking that you don’t need to localize your application, so this is not important to you. Ok, really what you are thinking is:

“I don’t know how to do it and if I ever get big enough to need localization, at that point, I will figure it out.”

Well, what if I told you that using Resources.resx is extremely easy?

What if I told you that it hardly takes more time at all?

If it easy and hardly time consuming at all, you would do it, right? I would. Hence this post.

Step by step guide for Preparing your strings for locaization

I have a project called LicenseAgreementManager. Right now this only needs to display a license agreement in English, but maybe someday, this will need to display a license agreement in any language.

Preparation – Create a new project or use an existing project

In Visual Studio, create a new WPF Applcation project.

I named my project LicenseAgreementManager.

Right away, you already have at least one string statically entered into your XAML, the text for the window title.

Step 1 – Add all your strings to the Resources.resx file

  1. Double-click on Resources.resx in your WPF Project. This found under the ProjectName | Properties option in your Solution Explorer tree.
  2. Change the Access Modifier drop down menu from Internal to Public.
  3. Enter your strings in the Resources.resx by giving them a unique name and a value of the desired string. A comment is also optional.

You now have a publicized Resource.resx file and a few strings inside it.

Step 2 – Add a reference to your Properties

  1. In your project, open your MainWindow.xaml file.The XAML looks as follows:
    <Window x:Class="LicenseAgreementManager.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" Height="350" Width="525">
        <Grid>
    
        </Grid>
    </Window>
    
  2. Add a line to reference your Properties in the Windows element.
    <Window x:Class="LicenseAgreementManager.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:p="clr-namespace:LicenseAgreementManager.Properties"
            Title="MainWindow" Height="350" Width="525">
    

Step 3 – Replace static text with strings from the Resources.resx

  1. Change the Title attribute from static text to instead use access the string from your Resources.resx named EULA_Title.
    <Window x:Class="LicenseAgreementManager.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:p="clr-namespace:LicenseAgreementManager.Properties"
            Title="{x:Static p:Resources.EULA_Title}"
            Height="350" Width="525">
    

That was pretty easy, wasn’t it.

As you add elements that have strings, use the Resources.resx.

Step 4 – Try to use dynamic sizing

  1. As best as possible, remove any dynamic sizing.I have just added some items and removed the sizing as best as possible. Here is my XAML.
    <Window x:Class="LicenseAgreementManager.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:p="clr-namespace:LicenseAgreementManager.Properties"
            Title="{x:Static p:Resources.EULA_Title}"
            SizeToContent="WidthAndHeight"
            xml:lang="en-US">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>
    
            <RichTextBox Name="_EulaTextBox" HorizontalAlignment="Stretch"  VerticalAlignment="Stretch"/>
            <StackPanel Grid.Row="1" Margin="0,10,0,0" Name="stackPanel2" HorizontalAlignment="Stretch"  VerticalAlignment="Stretch">
                <RadioButton Content="{x:Static p:Resources.EULA_Accept}" Margin="20,20,20,0" Name="radioButton1" />
                <RadioButton Content="{x:Static p:Resources.EULA_NotAccept}" Margin="20,20,20,0" Name="radioButton2" />
                <Button Content="{x:Static p:Resources.Next_Button}" Name="button1" Margin="20,20,35,20"  HorizontalAlignment="Right" />
            </StackPanel>
        </Grid>
    </Window>
    
  2. What changes did I make above that I couldn’t do through the Visual Studio GUI?
    1. I removed Height and size from almost every element.
    2. I added SizeToContent=”WidthAndHeight” to the Windows element.
    3. I added some extra size to the margins.

Conclusion

You don’t have to be localized to be prepared for easy localization. By doing the above simple steps, when it comes time to add localization, you will be ready.

If you want to go on an finish localization. You might want to read some of my sources.

Sources:

http://compositeextensions.codeplex.com/Thread/View.aspx?ThreadId=52910
http://msdn.microsoft.com/en-us/library/ms788718%28v=VS.90%29.aspx
http://msdn.microsoft.com/en-us/library/ms746621.aspx


Copyright ® Rhyous.com – Linking to this article is allowed without permission and as many as ten lines of this article can be used along with this link. Any other use of this article is allowed only by permission of Rhyous.com.

10 Comments

  1. RaymondFum says:

    Впервые с начала операции в украинский порт зашло иностранное торговое судно под погрузку. По словам министра, уже через две недели планируется выползти на уровень по меньшей мере 3-5 судов в сутки. Наша функция – выход на месячный объем перевалки в портах Большой Одессы в 3 млн тонн сельскохозяйственной продукции. По его словам, на сборе в Сочи президенты компостировали поставки российского газа в Турцию. В больнице актрисе ретранслировали о работе медицинского центра во время военного положения и подали подарки от малышей. Благодаря этому мир еще крепче будет слышать, знать и понимать правду о том, что продолжается в нашей стране.

  2. Ben Glancy says:

    Soooo you give the resx files to your translation guys?

  3. steve says:

    cheers that really helped

  4. Custom Glass Products-CGP says:

    Custom Glass Products-CGP

    Tutorial - Binding to Resources.resx for strings in a WPF Application: A technique to prepare for localization | Rhyous

  5. Ness says:

    I use https://poeditor.com/ to localize my resx files. I recommend it to you guys also, it's easy to work with and very fast. It works both with auto translations and crowd translators.

  6. Saleha Shaikh says:

    Nice solution 🙂 really helped

  7. Petteri says:

    Great tutorial! Useful tip is to use service like Get Localization http://www.getlocalization.com. Just upload your RESX file there and that's it. Much easier for translators to work as it hides completely the complexity involved handling these files.

Leave a Reply to Saleha Shaikh

How to post code in comments?