有没有办法在我的WPF应用程序中独立于StringFormat
为全局DateTime
对象设置CultureInfo
?
我在整个应用程序中使用绑定到这种对象,如下所示:
<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应用程序中独立于
StringFormat
为全局所有DateTime
对象设置CultureInfo
一个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)));
}
}