我想在WPF应用程序中更改DateTimePicker选择的日期格式
我想在WPF应用程序中更改DateTimePicker选择的日期格式
最近我在处理这个问题。我找到了一种简单的方法来执行此自定义格式,我希望这能帮到你。首先,您需要在XAML中为当前的DatePicker应用特定的样式,就像这样:
<DatePicker.Resources>
<Style TargetType="{x:Type DatePickerTextBox}">
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate>
<TextBox x:Name="PART_TextBox" Width="113" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" Text="{Binding Path=SelectedDate,Converter={StaticResource DateTimeFormatter},RelativeSource={RelativeSource AncestorType={x:Type DatePicker}},ConverterParameter=dd-MMM-yyyy}" BorderBrush="{DynamicResource BaseBorderBrush}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</DatePicker.Resources>
在这一部分中,您可以注意到存在一个名为DateTimeFormatter的转换器,用于将绑定到“PART_TextBox”的Text属性。该转换器接收包含自定义格式的转换器参数。最后,我们添加了C#中的DateTimeFormatter转换器代码。
public class DateTimeConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
DateTime? selectedDate = value as DateTime?;
if (selectedDate != null)
{
string dateTimeFormat = parameter as string;
return selectedDate.Value.ToString(dateTimeFormat);
}
return "Select Date";
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
try
{
var valor = value as string;
if (!string.IsNullOrEmpty(valor))
{
var retorno = DateTime.Parse(valor);
return retorno;
}
return null;
}
catch
{
return DependencyProperty.UnsetValue;
}
}
}
我希望这对你有所帮助。如果有任何问题或建议改进,请告诉我。
Thread.CurrentThread.CurrentCulture = (CultureInfo)Thread.CurrentThread.CurrentCulture.Clone();
Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern = "dd-MMM-yyyy";
将以下样式添加到您的XAML或App.xaml文件中
<Style TargetType="{x:Type DatePickerTextBox}">
<Setter Property="VerticalContentAlignment" Value="Center"/>
<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>
<toolkit:DatePicker SelectedDateFormat="Long" />
或者
<toolkit:DatePicker SelectedDateFormat="Short" />
感谢@Fernando García提供的基础。
我为DatePicker编写了一个DateFormat附加属性,让您可以提供一个格式字符串来显示和输入日期。
对于输入,它将尝试使用提供的格式进行解析,如果失败,则尝试使用当前文化的格式进行解析。
以下是使用此格式的示例:
<DatePicker my:DatePickerDateFormat.DateFormat="dd/MMM/yyyy"/>
public class DatePickerDateFormat
{
public static readonly DependencyProperty DateFormatProperty =
DependencyProperty.RegisterAttached("DateFormat", typeof (string), typeof (DatePickerDateFormat),
new PropertyMetadata(OnDateFormatChanged));
public static string GetDateFormat(DependencyObject dobj)
{
return (string) dobj.GetValue(DateFormatProperty);
}
public static void SetDateFormat(DependencyObject dobj, string value)
{
dobj.SetValue(DateFormatProperty, value);
}
private static void OnDateFormatChanged(DependencyObject dobj, DependencyPropertyChangedEventArgs e)
{
var datePicker = (DatePicker) dobj;
Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.Loaded, new Action<DatePicker>(ApplyDateFormat), datePicker);
}
private static void ApplyDateFormat(DatePicker datePicker)
{
var binding = new Binding("SelectedDate")
{
RelativeSource = new RelativeSource {AncestorType = typeof (DatePicker)},
Converter = new DatePickerDateTimeConverter(),
ConverterParameter = new Tuple<DatePicker, string>(datePicker, GetDateFormat(datePicker))
};
var textBox = GetTemplateTextBox(datePicker);
textBox.SetBinding(TextBox.TextProperty, binding);
textBox.PreviewKeyDown -= TextBoxOnPreviewKeyDown;
textBox.PreviewKeyDown += TextBoxOnPreviewKeyDown;
datePicker.CalendarOpened -= DatePickerOnCalendarOpened;
datePicker.CalendarOpened += DatePickerOnCalendarOpened;
}
private static TextBox GetTemplateTextBox(Control control)
{
control.ApplyTemplate();
return (TextBox) control.Template.FindName("PART_TextBox", control);
}
private static void TextBoxOnPreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key != Key.Return)
return;
/* DatePicker subscribes to its TextBox's KeyDown event to set its SelectedDate if Key.Return was
* pressed. When this happens its text will be the result of its internal date parsing until it
* loses focus or another date is selected. A workaround is to stop the KeyDown event bubbling up
* and handling setting the DatePicker.SelectedDate. */
e.Handled = true;
var textBox = (TextBox) sender;
var datePicker = (DatePicker) textBox.TemplatedParent;
var dateStr = textBox.Text;
var formatStr = GetDateFormat(datePicker);
datePicker.SelectedDate = DatePickerDateTimeConverter.StringToDateTime(datePicker, formatStr, dateStr);
}
private static void DatePickerOnCalendarOpened(object sender, RoutedEventArgs e)
{
/* When DatePicker's TextBox is not focused and its Calendar is opened by clicking its calendar button
* its text will be the result of its internal date parsing until its TextBox is focused and another
* date is selected. A workaround is to set this string when it is opened. */
var datePicker = (DatePicker) sender;
var textBox = GetTemplateTextBox(datePicker);
var formatStr = GetDateFormat(datePicker);
textBox.Text = DatePickerDateTimeConverter.DateTimeToString(formatStr, datePicker.SelectedDate);
}
private class DatePickerDateTimeConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var formatStr = ((Tuple<DatePicker, string>) parameter).Item2;
var selectedDate = (DateTime?) value;
return DateTimeToString(formatStr, selectedDate);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
var tupleParam = ((Tuple<DatePicker, string>) parameter);
var dateStr = (string) value;
return StringToDateTime(tupleParam.Item1, tupleParam.Item2, dateStr);
}
public static string DateTimeToString(string formatStr, DateTime? selectedDate)
{
return selectedDate.HasValue ? selectedDate.Value.ToString(formatStr) : null;
}
public static DateTime? StringToDateTime(DatePicker datePicker, string formatStr, string dateStr)
{
DateTime date;
var canParse = DateTime.TryParseExact(dateStr, formatStr, CultureInfo.CurrentCulture,
DateTimeStyles.None, out date);
if (!canParse)
canParse = DateTime.TryParse(dateStr, CultureInfo.CurrentCulture, DateTimeStyles.None, out date);
return canParse ? date : datePicker.SelectedDate;
}
}
}
DatePicker1.SelectedDate = DatePicker1.SelectedDate.Value.ToString("dd/MM/yyyy")
对我而言,为了改变DatePicker
格式(例如Thread.CurrentCulture
),改变环境并不是一个好主意。
当然,你可以创建从DatePicker
派生的Control
,并实现像Format
这样的依赖属性,但这需要太多的努力。
我发现的简单而优雅的解决方案是将值绑定到某个未使用的属性(我使用ToolTip
属性),并在更改SelectedDate
时更新此属性。
一种单向绑定的C#实现如下:
DatePicker datePicker = new DatePicker();
datePicker.SetBinding(ToolTipProperty, "Date");
datePicker.SelectedDateChanged += (s, ea) =>
{
DateTime? date = datePicker.SelectedDate;
string value = date != null ? date.Value.ToString("yyyy-MM-dd") : null;
datePicker.ToolTip = value;
};
XAML+C# 应该长这样:
XAML:
<DatePicker ToolTip="{Binding Date Mode=TwoWay}"
SelectedDateChanged="DatePicker_SelectedDateChanged"/>
C#:
private void DatePicker_SelectedDateChanged(object sender, EventArgs ea)
{
DatePicker datePicker = (DatePicker)sender;
DateTime? date = datePicker.SelectedDate;
string value = date != null ? date.Value.ToString("yyyy-MM-dd") : null;
datePicker.ToolTip = value;
}
对于双向实现,处理ToolTipChanged
事件的方式相同,以更新SelectedDate
。
试一下
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
DateLabel.Content = Convert.ToDateTime(datePicker1.Text).ToString("dd-MM-yyyy");
}
ToString(DATE_FORMAT)
。dateTimePicker.SelectedDate.ToString("dd-MMM-yyyy");