Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Dynamically changing menu items according to CultureInfo

0.00/5 (No votes)
29 Jun 2006 1  
An article on how to change the text of menu items and other controls on changing the current language settings.

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];
    
    //info can be Button, Menuitem, ToolbarButton.....

    //info.Name returns true name of control

    //        - menuItem1, btnChangelanguage....

    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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here