2009-09-02 44 views
1

我想檢測區域設置的變化,並在WPF應用程序中以正確的格式顯示日期。但CultureInfo.ClearCachedData存在一個奇怪的問題。它隨機要麼不工作。有人知道爲什麼,併爲此解決方法嗎?我知道區域設置存儲在註冊表中,但它太原始,無法破譯HKCU \ Control Panel \ International的內容,並通過它手動構建CultureInfo。CultureInfo.ClearCachedData不起作用。它隨機有時有時不工作

我已經把它放在一個更大的應用程序中,CultureInfo.ClearCachedData失敗率幾乎是100%。

Window1.xaml.cs:

using System; 
using System.Globalization; 
using System.Windows; 
using System.Windows.Interop; 

namespace WpfApplication1 
{ 
    partial class Window1 : Window 
    { 
     int i = 0; 

     public Window1() 
     { 
      InitializeComponent(); 
      ShownCurrentCulture(); 
      Loaded += (x, y) => HwndSource.FromHwnd(
       new WindowInteropHelper(this).Handle).AddHook(WndProc); 
     } 

     IntPtr WndProc(IntPtr hwnd, int msg, 
      IntPtr wParam, IntPtr lParam, ref bool handled) 
     { 
      if (msg == 0x1a) // WM_SETTINGCHANGE 
      { 
       // CultureInfo.CurrentCulture is sometimes changed, 
       // sometimes not 
       ShownCurrentCulture(); 
      } 
      return IntPtr.Zero; 
     } 

     void ShownCurrentCulture() 
     { 
      CultureInfo.CurrentCulture.ClearCachedData(); 
      Title = i++ + " " + CultureInfo.CurrentCulture; 
     } 
    } 
} 

回答

2

一些更多的試驗,我發現,只有新創建的線程正確地獲得更新的培養後。舊線程的CultureInfo.CurrentCulture會隨機返回舊的(Thread.CurrentThread.CurrentCulture)或更新後的文化。

很可能如果修改了Thread.CurrentThread.CurrentCulture,CultureInfo.CurrentCulture在調用ClearCachedData後不會更新,否則它會被更新。