Changing the string format of the WPF DatePicker

前端 未结 9 1731
广开言路
广开言路 2020-11-27 14:56

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

相关标签:
9条回答
  • 2020-11-27 15:20

    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"/>
    
    0 讨论(0)
  • 2020-11-27 15:21

    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)

    0 讨论(0)
  • 2020-11-27 15:27

    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();
            }
            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
    {
        /// <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
    }
    
    0 讨论(0)
  • 2020-11-27 15:28

    XAML

     <DatePicker x:Name="datePicker" />
    

    C#

    var date = Convert.ToDateTime(datePicker.Text).ToString("yyyy/MM/dd");
    

    put what ever format you want in ToString("") for example ToString("dd MMM yyy") and output format will be 7 Jun 2017

    0 讨论(0)
  • 2020-11-27 15:34

    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>
    
    0 讨论(0)
  • 2020-11-27 15:35

    Converter class:

    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

    0 讨论(0)
提交回复
热议问题