我想检测区域设置的变化,并在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;
}
}
}