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>
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);
See LanguageManager for more info
Add translations
IDE support adding resources over UI:
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)
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.
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
Is there any way to refresh the strings set this way without restarting the application?
Yes, but not native, we have to do the logic separately