输入后,DatePicker从dd / MM / yyyy更改为MM / dd / yyyy

时间:2019-06-03 16:11:09

标签: c# wpf date datepicker cultureinfo

我正在做一个wpf应用程序,我必须在两个字段中输入如下日期:dd/MM/yyyy hh:mm:ss,但是当我失去对元素的关注时,日期将转到MM/dd/yyyy hh:mm:ss。而且只有在我更改日期时才会发生这种情况。 如果我将月份和日期切换更改为一秒钟。

如果我失去焦点时输入“ 03/06/2019 16:58:00”,则日期为“ 06/03/2019 16:58:00”。而这在POPUP中发生了变化。

问题不是在格式上,而是在显示顺序上。

我的XAML是这样的:

<DatePicker x:Name="Dp_DataInicio" Grid.Row="0" Grid.Column="2" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="10,211,0,0" FontSize="16" Height="20" Width="230" IsTodayHighlighted="False" BorderThickness="0" Padding="0" BorderBrush="{x:Null}" IsTabStop="True" Visibility="Hidden" SelectedDateChanged="Dp_DataInicio_SelectedDateChanged">
   <DatePicker.Resources>
      <Style TargetType="{x:Type DatePickerTextBox}">
         <Setter Property="Control.Template">
            <Setter.Value>
               <ControlTemplate>
                  <TextBox x:Name="PART_TextBox" Text="{Binding Path=SelectedDate, RelativeSource={RelativeSource AncestorType={x:Type DatePicker}}, StringFormat='dd/MM/yyyy HH:mm:ss'}" Background="#FF494949" Foreground="#FFEEEEEE" BorderThickness="0" IsReadOnly="False"/>
               </ControlTemplate>
            </Setter.Value>
         </Setter>
      </Style>
   </DatePicker.Resources>
</DatePicker>

我拥有的C#就是这样:

private void Dp_DataInicio_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
{
    if (Dp_DataInicio.SelectedDate > DateTime.Now) //Set the date to Now if is supperior to Now
    {
        Dp_DataInicio.SelectedDate = null;
        Dp_DataInicio.DisplayDate = DateTime.Now;
        Lbl_Erros.Text = "A data de inicio não pode ser após a este momento!";
    }
    else if (Dp_DataInicio.SelectedDate == Convert.ToDateTime(null)) //Letting the user know he cant have a null date
    {
        Dp_DataInicio.SelectedDate = null;
        Dp_DataInicio.DisplayDate = DateTime.Now;
        Lbl_Erros.Text = "A data de inicio tem de ter um valor.";
    }
    else if (Dp_DataInicio.SelectedDate >= Dp_DataFim.SelectedDate && Dp_DataFim.SelectedDate != Convert.ToDateTime(null)) //Not letting the beggining date be supperior to the finishing date
    {
        Dp_DataInicio.SelectedDate = null;
        Dp_DataInicio.DisplayDate = DateTime.Now;
        Lbl_Erros.Text = "A data de inicio não pode ser após a data de fim";
    }
    else //If it's all ok
    {
        Lbl_Erros.Text = null;
    }

    DateTime value;
    //Its Valid date
    if (DateTime.TryParse(Dp_DataInicio.Text, out value))
    {
        DataInicioValido = true;
    }
    else
    {
        DataInicioValido = false;
    }

    AtualizarBotoes(); //Change the state of other buttons
}

日期始终为dd/MM/yyyy hh:mm:ss格式,但是它会更改元素失去焦点的月份和日期的顺序。却像这样dd/MM/yyyy hh:mm:ss

1 个答案:

答案 0 :(得分:0)

正如Jeff R所说,解决方案在这篇文章(https://stackoverflow.com/a/16565917/9925729)中 为了使其正常工作,需要添加using System.Windows.Markup;和代码

this.Language = XmlLanguage.GetLanguage("fr-FR");

InitializeComponent();

之后
相关问题