为所有 DateTime 对象全局设置字符串格式,独立于区域性信息 - WPF



有没有办法独立于 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对象没有任何StringFormatBinding有。您可以创建自定义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;
}

相关内容

  • 没有找到相关文章

最新更新