DEV Community

Cover image for Localization in AvaloniaUI
Ingvar
Ingvar

Posted on

Localization in AvaloniaUI

Hey there! This time I gonna explain how to add localization support in your AvaloniaUI app. As always I'm using my app called Camelot as good working example.

What is localization and why do we need it

Localization is a process of adding support for different locales in your app. Locales always include language, date/time formats etc. It allows users from multiple countries use your app in their native language.

How to localize AvaloniaUI app

Create resources

First step is to create set of resources files like here. It could be done automatically via IDE. Resources.resx is the main file with default culture translations inside, IDE also autogenerates Resources.Designer.cs class based on it. This class could be used in code if needed. Other *.resx files contain translations for different cultures etc. Please note that for same language it's possible to keep many locales, like en-US and en-GB.

Integrate resources into views

Resources could be used as static objects in views. Translation for current locale will be shown. Here is an example how to use them:



<ToolTip.Tip>
    <TextBlock Classes="mainWindowTextBlock" Text="{x:Static p:Resources.GoBack}" />
</ToolTip.Tip>


Enter fullscreen mode Exit fullscreen mode

Add language selection logic

For usability it's good to provide ability to select language in UI. All you need on backend in this case is to set current culture:



Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(languageCode);


Enter fullscreen mode Exit fullscreen mode

See LanguageManager for more info

Add translations

IDE support adding resources over UI:

Alt Text

Tips: use clear translation string names. If text is too long don't try to put full text in resource name. If you have resource that ends with colon I recommend to name it ...WithColon because you might need similar resource w/o colon later and adding : in view to your text won't work for some locales as expected.

Conclusion

In this post I described process of localization AvaloniaUI app. It's pretty straight-forward process. Feel free to contact me in comments if you have any questions!

Top comments (4)

Collapse
 
littleyan profile image
Unmeltable-Ice

Thanks for sharing, solved my problem:)
One small additional remark: Make sure the "Access Modifier" in main file Resources.resx is "Public", not the default value "Internal" in Visual Studio.

Collapse
 
yusuke1998 profile image
JhonnyPrz

In rider it is also by default Internal, it caused me a lot of problems a few days ago, until I saw what that was xD

Collapse
 
zsuatem profile image
Mateusz Pawłowski

Is there any way to refresh the strings set this way without restarting the application?

Collapse
 
yusuke1998 profile image
JhonnyPrz

Yes, but not native, we have to do the logic separately