Introduction
I have been working on applications where users have the possibility to change language options (as customers are from different countries). .NET has excellent localization support for every part of an application, by using .resx files and creating .dlls for each supported language, but I found one problem. After setting a new language on the appropriate dialog, every new form would be correct, except the main application form. Menus, toolbars, and other elements would only change on the next application start. Since that was not good enough for me, I found a solution for the problem.
Using the code
The idea was to get new text from the ResourceManager (like InitializeComponent
does). But in that case, we must have the control names (menuItem1
, in this case). So, we'll use reflection to get the list of FiledInfo
in the main app window. After that, we'll run through the list and if FiledInfo
is some control that requires translation, we'll take the control's Name
and use it for the ResourceManager call.
System.Reflection.FieldInfo[] fi =
this.GetType().GetFields(BindingFlags.Public |
BindingFlags.Instance | BindingFlags.NonPublic);
for (int i = 0; i < fi.Length; ++i)
{
FieldInfo info = fi[i];
if (typeof(MenuItem) == info.FieldType)
{
MenuItem item = (MenuItem)info.GetValue(this);
item.Text = resources.GetString(info.Name + ".Text");
}
}
About reflection
Reflection is a very powerful tool, but must be used carefully, because it can be slow. But for this kind of a problem, it's a simple and elegant solution.