CultureInfo.ClearCachedData不起作用。它随机有时有时不起作用

时间:2009-09-02 22:43:26

标签: c# wpf datetime localization

我想检测区域设置更改并在WPF应用程序中以正确的格式显示日期。但是CultureInfo.ClearCachedData存在一个奇怪的问题。它可以随机地工作。有人知道为什么,以及解决方法吗?我知道区域设置存储在注册表中,但它太过于原始,无法解密 HKCU \ Control Panel \ International 的内容并从中手动构建CultureInfo。

我把它放在一个更大的应用程序中,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;
        }
    }
}

1 个答案:

答案 0 :(得分:2)

经过一些试验后,我发现只有新创建的线程才能正确获得更新的文化。旧线程上的CultureInfo.CurrentCulture随机返回旧的(Thread.CurrentThread.CurrentCulture)或更新的文化。

如果修改了Thread.CurrentThread.CurrentCulture,在调用ClearCachedData之后,CultureInfo.CurrentCulture将不会在该步骤中更新,否则会更新。