2010-08-24 87 views
9

我有一個winforms應用程序,用戶必須能夠在運行時更改語言。如何在運行時更改語言而無佈局問題

爲了概括開關,避免硬編碼控制的名字我嘗試以下擴展名:

internal static void SetLanguage(this Form form, CultureInfo lang) 
    { 
     ComponentResourceManager resources = new ComponentResourceManager(form.GetType()); 

     ApplyResourceToControl(resources, form, lang); 
     resources.ApplyResources(form, "$this", lang); 
    } 

    private static void ApplyResourceToControl(ComponentResourceManager resources, Control control, CultureInfo lang) 
    { 
     foreach (Control c in control.Controls) 
     { 
      ApplyResourceToControl(resources, c, lang); 
      resources.ApplyResources(c, c.Name, lang); 
     } 
    } 

這不會改變所有的字符串。

但是,其副作用是窗口的全部內容被調整爲該窗口的原始啓動大小,無論當前大小是多少。

如何防止佈局更改或啓動新的佈局計算?

+0

我希望我可以投票給你更多,然後一次很有幫助! – Bosak 2012-09-24 19:10:31

回答

5

查看.resx文件以查看所有重新分配的內容。諸如Size和Form.AutoScaleDimensions之類的屬性是可本地化的屬性。重新分配它們具有你所看到的那種效果。特別是取消自動縮放會非常不愉快。

沒有具體的建議來解決這個問題,這只是不能在窗體構造函數以外的任何其他地方運行。重建表單。指出你的表單的實際用戶永遠不會覺得有必要即時改變她的母語,似乎從來沒有給人留下印象。

5

這是我現在使用的完整代碼。

更改是僅手動更改Text屬性。如果我需要本地化其他屬性,那麼代碼將不得不在之後擴展。

/// <summary> 
    /// Change language at runtime in the specified form 
    /// </summary> 
    internal static void SetLanguage(this Form form, CultureInfo lang) 
    { 
     //Set the language in the application 
     System.Threading.Thread.CurrentThread.CurrentUICulture = lang; 

     ComponentResourceManager resources = new ComponentResourceManager(form.GetType()); 

     ApplyResourceToControl(resources, form.MainMenuStrip, lang); 
     ApplyResourceToControl(resources, form, lang); 

     //resources.ApplyResources(form, "$this", lang); 
     form.Text = resources.GetString("$this.Text", lang); 
    } 

    private static void ApplyResourceToControl(ComponentResourceManager resources, Control control, CultureInfo lang) 
    { 
     foreach (Control c in control.Controls) 
     { 
      ApplyResourceToControl(resources, c, lang); 
      //resources.ApplyResources(c, c.Name, lang); 
      string text = resources.GetString(c.Name+".Text", lang); 
      if (text != null) 
       c.Text = text; 
     } 
    } 

    private static void ApplyResourceToControl(ComponentResourceManager resources, MenuStrip menu, CultureInfo lang) 
    { 
     foreach (ToolStripItem m in menu.Items) 
     { 
      //resources.ApplyResources(m, m.Name, lang); 
      string text = resources.GetString(m.Name + ".Text", lang); 
      if (text != null) 
       m.Text = text; 
     } 
    }