65.9K
CodeProject is changing. Read more.
Home

Dynamically changing menu items according to CultureInfo

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.93/5 (9 votes)

Jun 29, 2006

1 min read

viewsIcon

30176

downloadIcon

424

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.