更改 WPF DatePicker 的字符串格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3819832/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Changing the string format of the WPF DatePicker
提问by benPearce
I need to change the string format of the DatePickerTextBox in the WPF Toolkit DatePicker, to use hyphens instead of slashes for the seperators.
我需要更改 WPF Toolkit DatePicker 中 DatePickerTextBox 的字符串格式,以使用连字符而不是分隔符的斜杠。
Is there a way to override this default culture or the display string format?
有没有办法覆盖这个默认文化或显示字符串格式?
01-01-2010
回答by petrycol
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>
回答by benPearce
It appears, as per Wonko's answer, that you cannot specify the Date format in Xaml format or by inheriting from the DatePicker.
根据 Wonko 的回答,您似乎无法以 Xaml 格式或通过从 DatePicker 继承来指定日期格式。
I have put the following code into my View's constructor which overrides the ShortDateFormat for the current thread:
我已将以下代码放入视图的构造函数中,该构造函数覆盖了当前线程的 ShortDateFormat:
CultureInfo ci = CultureInfo.CreateSpecificCulture(CultureInfo.CurrentCulture.Name);
ci.DateTimeFormat.ShortDatePattern = "dd-MM-yyyy";
Thread.CurrentThread.CurrentCulture = ci;
回答by MarkB
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.
接受的答案(感谢@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>
回答by Jordan Parmer
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.
WPF 工具包DateTimePicker
现在有一个Format
属性和一个FormatString
属性。如果指定Custom
为格式类型,则可以提供自己的格式字符串。
<wpftk:DateTimePicker
Value="{Binding Path=StartTime, Mode=TwoWay}"
Format="Custom"
FormatString="MM/dd/yyyy hh:mmtt"/>
回答by Wonko the Sane
NOTE: This answer (originally written in 2010) is for earlier versions. See other answers for using a custom format with newer versions
注意:这个答案(最初写于 2010 年)适用于早期版本。请参阅有关在较新版本中使用自定义格式的其他答案
Unfortunately, if you are talking about XAML, you are stuck with setting SelectedDateFormat to "Long" or "Short".
不幸的是,如果您在谈论 XAML,您会被困在将 SelectedDateFormat 设置为“Long”或“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:
如果您下载了 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
日期选择器格式.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
}
回答by Usman Ali
XAML
XAML
<DatePicker x:Name="datePicker" />
C#
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
把你想要的任何格式放在 ToString("") 例如 ToString("dd MMM yyy") 和输出格式将是 7 Jun 2017
回答by alkk
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
wpf 标签
<DatePicker Grid.Column="3" SelectedDate="{Binding DateProperty, Converter={StaticResource DateFormat}}" Margin="5"/>
Hope it helps
希望能帮助到你
回答by Denis Prohorchik
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)
你会幸福的!(dd'-'MM'-'yyy)