2009-09-02 42 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后不会更新,否则它会被更新。