What is the best way to implement multi-language in XAML app? #16445
-
I want to be able to change language on the fly. I have two variants in my mind:
Maybe somethign else? What is the best case? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
I guess i should be using smth like this https://www.sakya.it/wordpress/avalonia-ui-framework-localization/ |
Beta Was this translation helpful? Give feedback.
-
To begin, there is no best way. But many opinions and options. As my opinion, I don't think language should rely on DI, as any other View-layer part of the codebase. Your first option is perfectly fine, although I would hide it under custom markup extension that returns the same Binding from ProvideValue, with single key parameter. If you insist, the same markup extension could use DI locator, yes.
Bindings themselves shouldn't leak in any case. But control instances might, but you just shouldn't keep static strong references on them in the code. |
Beta Was this translation helpful? Give feedback.
-
Firsly, I created an extension like this:
Then I created a helper:
I stored multi-language data in different json files, such as en.json. you must use the Initialize method in LocalizationHelper to initialize multi-language data. The key in the dictionary is the only key, and the value is the translation of the corresponding language. For example, if the key is HelloWorld, the corresponding value for English is Hello World, and the corresponding value for Chinese is 你好世界. ps: FrozenDictionary is a new feature of .NET8. It is more efficient to use FrozenDictionary for fixed data. Of course, if you are not using .NET8, you can use the normal Dictionary. In XAML, you can use it like this: You might ask, why did I split it into two separate classes? Because on the backend, if you want to get multilingual data, you can do it like this: Although my method is feasible, it has a fatal flaw, because it does not use binding on the front end, so when the language is changed, the program needs to be restarted for it to take effect. |
Beta Was this translation helpful? Give feedback.
Firsly, I created an extension like this:
Then I created a helper: