【问题标题】:Updating the date format in a DatePicker when the system date format is changed at runtime在运行时更改系统日期格式时更新 DatePicker 中的日期格式
【发布时间】:2012-05-23 08:37:58
【问题描述】:

我正在 WPF 应用程序中使用 DatePicker。我想把DatePicker的日期格式改成系统日期格式。

这是邮件窗口:

<Window x:Class="DateTimeDemo.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <Button x:Name="Btn" Width="100" Click="Btn_Click">Click</Button>
    </StackPanel>
</Window>

使用以下代码打开子窗口:

private void Btn_Click(object sender, RoutedEventArgs e)
{
    ChiildWindow Cw = new ChiildWindow();
    Cw.ChildDatePicker.SelectedDate = DateTime.Now;
    Cw.ShowDialog();
    Cw.Focus();
}

这是子窗口,它只包含一个DatePicker:

<Window x:Class="DateTimeDemo.ChiildWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="ChiildWindow" Height="300" Width="300">
    <StackPanel>
        <DatePicker x:Name="ChildDatePicker"/>
    </StackPanel>
</Window>

当我打开子窗口时,格式取自系统区域性,但如果我在窗口打开后从控制面板更改系统日期格式,则格式不会改变。

我在 ChildWindow.xaml.cs 文件中尝试了以下代码:

Thread.CurrentThread.CurrentCulture = CultureInfo.CurrentCulture;

但是当我打开子窗口时,格式并没有改变。

有谁知道问题是什么以及如何解决这个问题?

【问题讨论】:

  • 您的问题到底是什么?您是否通过在后面的代码中分配 CurrentCulture 解决了这个问题?
  • 不,我已经写过这个问题还没有解决..我已经尝试过这些事情但还没有解决。你能帮帮我吗??

标签: wpf datepicker culture datetime-format


【解决方案1】:

根据这个答案(How to get current regional settings in C#?),您可以使用此代码检测文化:

private class State
{
    public CultureInfo Result { get; set; }
}

public CultureInfo GetCurrentCulture()
{
    Thread.CurrentThread.CurrentCulture.ClearCachedData();
    var thread = new Thread(s => ((State)s).Result = Thread.CurrentThread.CurrentCulture);
    var state = new State();
    thread.Start(state);
    thread.Join();
    var culture = state.Result;
}

最后,你需要设置 CurrentUICulture 属性来影响 UI 组件:

Thread.CurrentThread.CurrentUICulture = GetCurrentCulture();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多