代码之家  ›  专栏  ›  技术社区  ›  benPearce

更改WPF日期选择器的字符串格式

  •  41
  • benPearce  · 技术社区  · 14 年前

    我需要更改wpftoolkit DatePicker中DatePickerTextBox的字符串格式,以便在分隔符中使用连字符而不是斜杠。

    是否有方法覆盖此默认区域性或显示字符串格式?

    01-01-2010
    
    8 回复  |  直到 14 年前
        1
  •  104
  •   petrycol    13 年前

    我用这个代码解决了这个问题。希望它也能帮助你们。

    <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>
    
        2
  •  25
  •   benPearce    14 年前

    根据Wonko的回答,似乎不能用Xaml格式或从DatePicker继承来指定日期格式。

    我已将以下代码放入视图的构造函数中,该构造函数将覆盖当前线程的ShortDateFormat:

    CultureInfo ci = CultureInfo.CreateSpecificCulture(CultureInfo.CurrentCulture.Name);
    ci.DateTimeFormat.ShortDatePattern = "dd-MM-yyyy";
    Thread.CurrentThread.CurrentCulture = ci;
    
        3
  •  16
  •   Jordan Parmer    12 年前

    DateTimePicker 现在有一个 Format FormatString 财产。如果您指定 Custom 作为格式类型,您可以提供自己的格式字符串。

    <wpftk:DateTimePicker
        Value="{Binding Path=StartTime, Mode=TwoWay}"
        Format="Custom"
        FormatString="MM/dd/yyyy hh:mmtt"/>
    
        4
  •  14
  •   Mark    8 年前

    接受的答案(谢谢@petrycol)让我走上了正确的轨道,但我在实际的日期选择器中得到了另一个文本框边框和背景色。使用以下代码修复了它。

            <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>
    
        5
  •  6
  •   Wonko the Sane    7 年前

    注:这个答案(最初写于2010年)适用于早期版本。有关在较新版本中使用自定义格式的信息,请参阅其他答案

    如果您下载了工具箱的源代码以及二进制文件,您可以看到它是如何定义的。下面是该代码的一些亮点:

    日期选择器.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;
    }
    

    日期pickerformat.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
    }
    
        6
  •  2
  •   Usman Ali    8 年前

    XAML公司

     <DatePicker x:Name="datePicker" />
    

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

    在ToString(“”)中输入所需的格式,例如ToString(“dd-MMM-yyy”),输出格式为2017年6月7日

        7
  •  1
  •   alkk    10 年前

    转换器等级:

    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();
        }
    }
    

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

    希望有帮助

        8
  •  0
  •   Denis Prohorchik    10 年前

    显示的格式取决于位置,但可以通过以下方式避免:

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

        9
  •  0
  •   Renis1235    4 年前

    正如本·皮尔斯所回答的,我们可以使用 类来处理自定义格式, 我真的认为这是唯一合乎逻辑的方法。如果您有不同格式的DateTimePicker,则可以使用:

    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;
    

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