有没有办法独立于 WPF 应用程序中的CultureInfo
全局设置所有DateTime
对象的StringFormat
?
我使用绑定到整个应用程序中的此类对象,如下所示:
<DataGridTextColumn Header="Date" Binding="{Binding Date}"/>
并且我想避免将StringFormat
参数添加到每个绑定中。 我试图DateTimeFormat
参数覆盖当前的区域性,如下所示:
public void SetDateTimeFormat()
{
culture = Thread.CurrentThread.CurrentUICulture;
var newCulture = new CultureInfo(culture.Name);
// Set desired date format here
newCulture.DateTimeFormat.ShortDatePattern = "dd/MMM/YYYY";
newCulture.DateTimeFormat.LongDatePattern = "dd/MMM/YYYY";
newCulture.DateTimeFormat.ShortTimePattern = "dd/MMM/YYYY";
newCulture.DateTimeFormat.LongTimePattern = "dd/MMM/YYYY";
newCulture.DateTimeFormat.FullDateTimePattern = "dd/MMM/YYYY";
CultureInfo.DefaultThreadCurrentCulture = newCulture;
CultureInfo.DefaultThreadCurrentUICulture = newCulture;
Thread.CurrentThread.CurrentCulture = newCulture;
Thread.CurrentThread.CurrentUICulture = newCulture;
FrameworkElement.LanguageProperty.OverrideMetadata(
typeof(FrameworkElement),
new FrameworkPropertyMetadata(System.Windows.Markup.XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));
var lang = System.Windows.Markup.XmlLanguage.GetLanguage(newCulture.IetfLanguageTag);
FrameworkContentElement.LanguageProperty.OverrideMetadata(
typeof(System.Windows.Documents.TextElement),
new FrameworkPropertyMetadata(lang)
);
}
但它不起作用
有没有办法独立于 WPF 应用程序中的
CultureInfo
全局设置所有DateTime
对象的StringFormat
DateTime
对象没有任何StringFormat
但Binding
有。您可以创建自定义Binding
类:
public class MyCustomBinding : Binding
{
public MyCustomBinding(string path)
:base(path)
{
StringFormat = "yyyy-MM-dd";
}
}
用法:
<DataGridTextColumn Header="Date" Binding="{local:MyCustomBinding Date}"/>
或者,您可以设置元素的Language
属性:
<DataGrid x:Name="dg" Language="en">
您也可以对App.xaml.cs
中的所有元素全局执行此操作:
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
var culture = new CultureInfo("en");
FrameworkElement.LanguageProperty.OverrideMetadata(typeof(FrameworkElement),
new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(culture.IetfLanguageTag)));
}
}
in app.xaml.cs
public App()
{
CultureInfo ci = CultureInfo.CreateSpecificCulture(CultureInfo.CurrentCulture.Name);
ci.DateTimeFormat.ShortDatePattern = "M/d/yyyy";
Thread.CurrentThread.CurrentCulture = ci;
}