【问题标题】:Date Format issue with WPFWPF 的日期格式问题
【发布时间】:2018-02-27 13:36:32
【问题描述】:

在我的 wpf 应用程序中,我使用了DatePicker 控件。我对DatePicker 控件的格式有疑问。它没有采用我指定的形式,而是采用默认的系统格式。我在我的应用程序启动文件中设置了日期时间格式,如下所示,

 string currentCulture = AppSettings.Locale;
        CultureInfo ci = new System.Globalization.CultureInfo(currentCulture);
        ci.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";
        Thread.CurrentThread.CurrentUICulture = ci;

在 xaml 中,我设置了如下所示的选定日期

SelectedDate="{Binding DateOfBirth, StringFormat='DD/MM/YYYY', Mode=TwoWay}"

在样式中我设置了如下文本

Text="{Binding Path=SelectedDate, StringFormat='dd/MM/yyyy', 
                            RelativeSource={RelativeSource AncestorType={x:Type DatePicker}}}">

我还错过了什么?为什么格式没有改变?谁能帮我解决这个问题?

PS:我最近更新到 .net framework 版本 4.7

【问题讨论】:

  • 我通常在我的 MainWindows.xaml 中使用 <Window ...... Language="pt-BR" ...... > Language(我是巴西人),所以我不需要将日期格式设置为“dd/mm/yyyy”

标签: wpf datepicker .net-framework-version


【解决方案1】:

试试这个:

<DatePicker SelectedDate="{Binding DateOfBirth}">
    <DatePicker.Resources>
        <Style TargetType="{x:Type DatePickerTextBox}">
            <Setter Property="Control.Template">
                <Setter.Value>
                    <ControlTemplate>
                        <TextBox x:Name="PART_TextBox"
                                 Text="{Binding Path=SelectedDate, StringFormat='dd/MM/yyyy', 
                                 RelativeSource={RelativeSource AncestorType={x:Type DatePicker}}}" />
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </DatePicker.Resources>
</DatePicker>

【讨论】:

  • 我使用的和你在 ma 风格中建议的一样。选择时格式没问题,但是当日期选择器最后一次关注时,日期格式将根据系统焦点进行更改。
【解决方案2】:

如果我在 ma 启动文件中添加以下行,问题就会得到解决

Thread.CurrentThread.CurrentCulture = ci;

所以文化部分应该如下所示:

string currentCulture = AppSettings.Locale;
        CultureInfo ci = new System.Globalization.CultureInfo(currentCulture);
        ci.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";
        Thread.CurrentThread.CurrentUICulture = ci;
        Thread.CurrentThread.CurrentCulture = ci;

【讨论】:

    猜你喜欢
    • 2011-09-20
    • 2014-05-30
    • 2014-04-01
    • 1970-01-01
    • 2016-01-25
    相关资源
    最近更新 更多