我正在为使用 .NET 3.5 的应用程序添加本地化。该应用程序使用 MVVM 模式和一个命令来改变文化。除了 DatePicker 控件在我单击它之前不会更改语言之外,一切都运行良好。此时,选定的日期文本将正确更改。在我将月份向前或向后移动一次之前,控件中的下拉日历也不会更改语言。
运行命令以更改文化后,如何强制控件以正确的语言刷新?
我尝试了几件事但没有成功,包括:
- DatePickerControl.InvalidateVisual()
- DatePickerControl.UpdateLayout()
- 在 VM 中 SelectedDate 的 CultureChanged 事件上触发 NotifyPropertyChanged
- DatePickerControl.Dispatcher.Invoke(DispatcherPriority.Render,EmptyDelegate)
应用程序.xaml.cs
protected override void OnStartup(StartupEventArgs e)
{
ApplicationCulture.Instance.CultureChanged += Instance_CultureChanged;
base.OnStartup(e);
}
private void Instance_CultureChanged(object sender, CultureChangedEventArgs e)
{
System.Threading.Thread.CurrentThread.CurrentUICulture = e.Culture;
System.Threading.Thread.CurrentThread.CurrentCulture = e.Culture;
}
看法
<UserControl x:Class="ManageAppointmentsView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:toolkit="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit">
<StackPanel>
<TextBlock Margin="5" FontSize="15" Text="{Binding LocalizedResources.Resource.Date}" />
<toolkit:DatePicker SelectedDate="{Binding SelectedDate}" SelectedDateFormat="Long" FontSize="15" VerticalContentAlignment="Center"
DisplayDateStart="{Binding StartDate}" CalendarStyle="{StaticResource CalendarStyle}" x:Name="DatePickerControl" />
</StackPanel>
</UserControl>
视图模型命令
ChangeLanguageCommand = new SimpleCommand
{
ExecuteDelegate = x =>
{
var newCulture = x == null
? "en-US"
: x.ToString();
ApplicationCulture.Instance.CurrentCulture =
new CultureInfo(newCulture);
}
};
应用文化
public class ApplicationCulture : INotifyCultureChanged
{
private ApplicationCulture() { }
private static ApplicationCulture _instance;
public static ApplicationCulture Instance
{
get
{
if (_instance == null)
_instance = new ApplicationCulture();
return _instance;
}
}
private CultureInfo _currentCulture = CultureInfo.InvariantCulture;
public CultureInfo CurrentCulture
{
get { return _currentCulture; }
set
{
if (!CultureInfo.Equals(value, _currentCulture))
{
_currentCulture = value;
NotifyCultureChanged(value);
}
}
}
public event EventHandler<CultureChangedEventArgs> CultureChanged;
private void NotifyCultureChanged(CultureInfo culture)
{
if (CultureChanged != null)
CultureChanged(this, new CultureChangedEventArgs(culture));
}
}