I need to change the string format of the DatePickerTextBox in the WPF Toolkit DatePicker, to use hyphens instead of slashes for the seperators.
Is there a way to ov
NOTE: This answer (originally written in 2010) is for earlier versions. See other answers for using a custom format with newer versions
Unfortunately, if you are talking about XAML, you are stuck with setting SelectedDateFormat to "Long" or "Short".
If you downloaded the source of the Toolkit along with the binaries, you can see how it is defined. Here are some of the highlights of that code:
DatePicker.cs
#region SelectedDateFormat
///
/// Gets or sets the format that is used to display the selected date.
///
public DatePickerFormat SelectedDateFormat
{
get { return (DatePickerFormat)GetValue(SelectedDateFormatProperty); }
set { SetValue(SelectedDateFormatProperty, value); }
}
///
/// Identifies the SelectedDateFormat dependency property.
///
public static readonly DependencyProperty SelectedDateFormatProperty =
DependencyProperty.Register(
"SelectedDateFormat",
typeof(DatePickerFormat),
typeof(DatePicker),
new FrameworkPropertyMetadata(OnSelectedDateFormatChanged),
IsValidSelectedDateFormat);
///
/// SelectedDateFormatProperty property changed handler.
///
/// DatePicker that changed its SelectedDateFormat.
/// DependencyPropertyChangedEventArgs.
private static void OnSelectedDateFormatChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DatePicker dp = d as DatePicker;
Debug.Assert(dp != null);
if (dp._textBox != null)
{
// Update DatePickerTextBox.Text
if (string.IsNullOrEmpty(dp._textBox.Text))
{
dp.SetWaterMarkText();
}
else
{
DateTime? date = dp.ParseText(dp._textBox.Text);
if (date != null)
{
dp.SetTextInternal(dp.DateTimeToString((DateTime)date));
}
}
}
}
#endregion SelectedDateFormat
private static bool IsValidSelectedDateFormat(object value)
{
DatePickerFormat format = (DatePickerFormat)value;
return format == DatePickerFormat.Long
|| format == DatePickerFormat.Short;
}
private string DateTimeToString(DateTime d)
{
DateTimeFormatInfo dtfi = DateTimeHelper.GetCurrentDateFormat();
switch (this.SelectedDateFormat)
{
case DatePickerFormat.Short:
{
return string.Format(CultureInfo.CurrentCulture, d.ToString(dtfi.ShortDatePattern, dtfi));
}
case DatePickerFormat.Long:
{
return string.Format(CultureInfo.CurrentCulture, d.ToString(dtfi.LongDatePattern, dtfi));
}
}
return null;
}
DatePickerFormat.cs
public enum DatePickerFormat
{
///
/// Specifies that the date should be displayed
/// using unabbreviated days of the week and month names.
///
Long = 0,
///
/// Specifies that the date should be displayed
///using abbreviated days of the week and month names.
///
Short = 1
}