更改 WPF DatePicker 的字符串格式

发布于 2024-09-25 12:20:39 字数 145 浏览 9 评论 0原文

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

有没有办法覆盖这个默认区域性或显示字符串格式?

01-01-2010

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

作业与我同在 2024-10-02 12:20:39

我在这段代码的帮助下解决了这个问题。希望它也能对大家有所帮助。

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

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>
幸福丶如此 2024-10-02 12:20:39

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

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

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

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;
花间憩 2024-10-02 12:20:39

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

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

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"/>
兔小萌 2024-10-02 12:20:39

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

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>
是伱的 2024-10-02 12:20:39

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

不幸的是,如果您正在谈论 XAML,则您必须将 SelectedDateFormat 设置为“Long”或“Short”。

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

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
}

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
}
风铃鹿 2024-10-02 12:20:39

XAML

 <DatePicker x:Name="datePicker" />

C#

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

在 ToString("") 中放置您想要的任何格式,例如 ToString("dd MMM yyy") ,输出格式将为 7 Jun 2017

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

无所的.畏惧 2024-10-02 12:20:39

我已经用一种简单的方法解决了这个问题......设置选项语言控制。

I have solved this problem in an easy way ... Setting options Language in control.

爱的那么颓废 2024-10-02 12:20:39

转换器类:

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

希望有帮助

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

花伊自在美 2024-10-02 12:20:39

显示的格式取决于位置,但这可以通过编写以下内容来避免:

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

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

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)

爱你不解释 2024-10-02 12:20:39

正如 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"  />

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"  />
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文