Question

Is it possible to change the Language property of the Main Form via code? If so, how?

Details: In the Config file I have set a lang="EN". What I want is to use the Localization setting to change the Main Form dependent on this variable. I have set the Localizable property to True.

For example:

if (Config.lang == "FR")
{
    //change **Language** property to "French"
}
else
{
    //remain (Default)
}

The issue is that I don't see the Language property anywhere in the coding window no matter where I look so I'm wondering if it's even possible to do this.

Était-ce utile?

La solution

Because of the way resources are managed in .Net UI programs, the easiest way to do this is to set the thread locale appropriately right at the start of the program before you create any forms.

Firstly determine the culture you want from your config file:

CultureInfo culture = ... whatever

Then set the main thread's CurrentUICulture and CurrentCulture to that locale:

System.Threading.Thread.CurrentThread.CurrentUICulture = culture;
System.Threading.Thread.CurrentThread.CurrentCulture   = culture;

This code would go into program.cs at the start of Main().

Note that if you start any other threads that display any UI (or output any localised data), you will also need to do the same thing at the start of those threads.

Also note that a major limitation of this approach is that you cannot change the locale while the program is running and have the UI update to reflect it. You have to set the locale at the beginning of the program.

There are other solutions which avoid this limitation, but they are waaay more complicated.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top