更改WPF DatePicker的字符串格式

时间:2010-09-29 08:18:37

标签: wpf datepicker wpftoolkit

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

有没有办法覆盖这种默认文化或显示字符串格式?

01-01-2010

9 个答案:

答案 0 :(得分:88)

我已经借助此代码解决了这个问题。希望它也会帮助你们所有人。

<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>

答案 1 :(得分:22)

根据Wonko的回答,您似乎无法以Xaml格式指定日期格式或继承DatePicker。

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

CultureInfo ci = CultureInfo.CreateSpecificCulture(CultureInfo.CurrentCulture.Name);
ci.DateTimeFormat.ShortDatePattern = "dd-MM-yyyy";
Thread.CurrentThread.CurrentCulture = ci;

答案 2 :(得分:12)

WPF工具包DateTimePicker现在具有Format属性和FormatString属性。如果指定Custom作为格式类型,则可以提供自己的格式字符串。

<wpftk:DateTimePicker
    Value="{Binding Path=StartTime, Mode=TwoWay}"
    Format="Custom"
    FormatString="MM/dd/yyyy hh:mmtt"/>

答案 3 :(得分:10)

接受的答案(感谢@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>

答案 4 :(得分:6)

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

不幸的是,如果你在谈论XAML,你就会把SelectedDateFormat设置为“Long”或“Short”。

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

<强> 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
}

答案 5 :(得分:2)

XAML

 <DatePicker x:Name="datePicker" />

C#

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

在ToString(“”)中放置您想要的格式,例如ToString(“dd MMM yyy”),输出格式为2017年6月7日

答案 6 :(得分:1)

转换器类:

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标签

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

希望有所帮助

答案 7 :(得分:0)

根据位置展示格式,但可以通过以下方式避免这种情况:

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

你会很开心!(dd' - 'MM' - 'yyy)

答案 8 :(得分:0)

正如Ben Pearce回答的那样,我们可以使用 CultureInfo 类来处理自定义格式, 我真的认为这是唯一合乎逻辑的方法。如果您有不同的dateTimePickers和Format,则可以使用:

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;

然后您只需更改.xaml文档中的DateFormat。

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