【发布时间】:2019-06-03 16:11:09
【问题描述】:
我正在做一个 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.
【问题讨论】:
-
您正在更改用于编辑的文本框的格式,但不幸的是,控件本身仍在使用默认线程文化,并且无法提供自定义格式。如果您想要的格式遵循已知的文化,您可以在首次创建时将窗口设置为该文化(请参阅stackoverflow.com/questions/16565652/…)
-
不知道能不能用转换器stackoverflow.com/a/24415748/1237135
标签: c# wpf date datepicker cultureinfo