相关文章推荐
高大的高山  ·  【wpf】ListView 和 ...·  1 月前    · 
爱搭讪的蚂蚁  ·  WPF 和 Windows Forms ...·  5 天前    · 
低调的马克杯  ·  js 按钮穿透 ...·  1 年前    · 
想出家的乌龙茶  ·  HiveSql里group ...·  1 年前    · 
英勇无比的野马  ·  浅析Git ...·  2 年前    · 
重感情的板凳  ·  WIN10 ...·  2 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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 override this default culture or the display string format?

01-01-2010

I have solved this problem with a help of this code. Hope it will help you all as well.

<Style TargetType="{x:Type DatePickerTextBox}">
 <Setter Property="Control.Template">
  <Setter.Value>
   <ControlTemplate>
    <TextBox x:Name="PART_TextBox"
     Text="{Binding Path=SelectedDate, StringFormat='dd MMM yyyy', 
     RelativeSource={RelativeSource AncestorType={x:Type DatePicker}}}" />
   </ControlTemplate>
  </Setter.Value>
 </Setter>
</Style>
                thx, it helped me to fully solve to use the date picker to select only month. i quoted your xaml in stackoverflow.com/questions/1798513/…  .
– GameAlchemist
                Feb 15, 2013 at 20:36
                I can see a few problems with this approach, e.g.: 1. No "select date" watermark; 2. User entered date (Text) will not be reflected back to SelectedDate. @benPearce, do you have a better solution?
– Bolu
                Nov 21, 2014 at 12:34
                I have a problem with this solution when I try to edit the date manually/textually. The format I'm using is : dd/MM/yyyy. If I put "11/01/1", at losing focus, it will automatically change to 11/01/2001... If I put "11/01/201", at losing focus, it will automatically change to 11/01/0201...  All this to say that the behavior of this autocompletion is not predictable and I would like to disable this function ...  I would rather want an error if there is no 4 digits on the year ...
– Hyukchan Kwon
                May 11, 2017 at 14:51

It appears, as per Wonko's answer, that you cannot specify the Date format in Xaml format or by inheriting from the DatePicker.

I have put the following code into my View's constructor which overrides the ShortDateFormat for the current thread:

CultureInfo ci = CultureInfo.CreateSpecificCulture(CultureInfo.CurrentCulture.Name);
ci.DateTimeFormat.ShortDatePattern = "dd-MM-yyyy";
Thread.CurrentThread.CurrentCulture = ci;
                This is actually what I prefer as not only this makes the date format of the entire system consistent, I also notice that messing with datepicker style mess up things such as placeholder text.
– Jacky Cheng
                Feb 5, 2020 at 5:23
                Best and easy way ! Works across the application if this code is put in App.cs constructor :)
– Rao Arman
                Sep 19, 2020 at 8:24

The WPF Toolkit DateTimePicker now has a Format property and a FormatString property. If you specify Custom as the format type, you can provide your own format string.

<wpftk:DateTimePicker
    Value="{Binding Path=StartTime, Mode=TwoWay}"
    Format="Custom"
    FormatString="MM/dd/yyyy hh:mmtt"/>
                DateTimePicker is different from DatePicker, so this doesn't actually answer the question
– Mandemon
                Oct 24, 2019 at 4:53

The accepted answer (thanks @petrycol) put me on the right track, but I was getting another textbox border and background color within the actual date picker. Fixed it using the following code.

        <Style TargetType="{x:Type Control}" x:Key="DatePickerTextBoxStyle">
            <Setter Property="BorderThickness" Value="0"/>
            <Setter Property="VerticalAlignment" Value="Center"/>
            <Setter Property="Background" Value="{x:Null}"/>
        </Style>
        <Style TargetType="{x:Type DatePickerTextBox}" >
            <Setter Property="Control.Template">
                <Setter.Value>
                    <ControlTemplate>
                        <TextBox x:Name="PART_TextBox"
                             Text="{Binding Path=SelectedDate, StringFormat='dd-MMM-yyyy', RelativeSource={RelativeSource AncestorType={x:Type DatePicker}}}" Style="{StaticResource DatePickerTextBoxStyle}" >
                        </TextBox>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

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
/// <summary>
/// Gets or sets the format that is used to display the selected date.
/// </summary>
public DatePickerFormat SelectedDateFormat
    get { return (DatePickerFormat)GetValue(SelectedDateFormatProperty); }
    set { SetValue(SelectedDateFormatProperty, value); }
/// <summary>
/// Identifies the SelectedDateFormat dependency property.
/// </summary>
public static readonly DependencyProperty SelectedDateFormatProperty =
    DependencyProperty.Register(
    "SelectedDateFormat",
    typeof(DatePickerFormat),
    typeof(DatePicker),
    new FrameworkPropertyMetadata(OnSelectedDateFormatChanged),
    IsValidSelectedDateFormat);
/// <summary>
/// SelectedDateFormatProperty property changed handler.
/// </summary>
/// <param name="d">DatePicker that changed its SelectedDateFormat.</param>
/// <param name="e">DependencyPropertyChangedEventArgs.</param>
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();
            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
    /// <summary>
    /// Specifies that the date should be displayed 
    /// using unabbreviated days of the week and month names.
    /// </summary>
    Long = 0,
    /// <summary>
    /// Specifies that the date should be displayed 
    ///using abbreviated days of the week and month names.
    /// </summary>
    Short = 1
                There is an Exception here , please review you answer:  An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll String was not recognized as a valid DateTime.
– abdou_dev
                Sep 11, 2020 at 14:41
public class DateFormat : IValueConverter
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        if (value == null) return null;
        return ((DateTime)value).ToString("dd-MMM-yyyy");
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        throw new NotImplementedException();

wpf tag

<DatePicker Grid.Column="3" SelectedDate="{Binding DateProperty, Converter={StaticResource DateFormat}}" Margin="5"/>

Hope it helps

Format exhibited depending on the location but this can be avoided by writing this:

  ValueStringFormat="{}{0:MM'-'yy}" />

And you will be happy!(dd'-'MM'-'yyy)

As Ben Pearce answered we can use the CultureInfo Class to take care of the Custom Format, I really think is the only logical way. And if you have different dateTimePickers which have different Format, you can use:

CultureInfo ci = CultureInfo.CreateSpecificCulture(CultureInfo.CurrentCulture.Name);
ci.DateTimeFormat.LongDatePattern = "MMM.yyyy"; //This can be used for one type of DatePicker
ci.DateTimeFormat.ShortDatePattern = "dd.MMM.yyyy"; //for the second type
Thread.CurrentThread.CurrentCulture = ci;

And then you can just change the DateFormat in the .xaml document.

  <DatePicker Name="dateTimePicker1" SelectedDateFormat="Long"  />
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.