15 .net wpf datetime datetimepicker datetime-format
我想更改WPF应用程序中DateTimePicker中选择的日期格式
小智 14
我正在彻底处理这个问题.我发现了一种执行此自定义格式的简单方法,我希望这对您有所帮助.您需要做的第一件事是在您的XAML中将特定样式应用于当前的DatePicker:
<DatePicker.Resources>
<Style TargetType="{x:Type DatePickerTextBox}">
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate>
<TextBox x:Name="PART_TextBox" Width="113" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" Text="{Binding Path=SelectedDate,Converter={StaticResource DateTimeFormatter},RelativeSource={RelativeSource AncestorType={x:Type DatePicker}},ConverterParameter=dd-MMM-yyyy}" BorderBrush="{DynamicResource BaseBorderBrush}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</DatePicker.Resources>
Run Code Online (Sandbox Code Playgroud)
正如您在此部分所注意到的那样,当时存在一个名为DateTimeFormatter的转换器,以便绑定到"PART_TextBox"的Text属性.此转换器接收包含您的自定义格式的转换器参数.最后,我们在C#中为DateTimeFormatter转换器添加代码.
public class DateTimeConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
DateTime? selectedDate = value as DateTime?;
if (selectedDate != null)
{
string dateTimeFormat = parameter as string;
return selectedDate.Value.ToString(dateTimeFormat);
}
return "Select Date";
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
try
{
var valor = value as string;
if (!string.IsNullOrEmpty(valor))
{
var retorno = DateTime.Parse(valor);
return retorno;
}
return null;
}
catch
{
return DependencyProperty.UnsetValue;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我希望这对你有所帮助.如有任何问题或建议改进,请告诉我.
小智 5
Thread.CurrentThread.CurrentCulture = (CultureInfo)Thread.CurrentThread.CurrentCulture.Clone();
Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern = "dd-MMM-yyyy";
Run Code Online (Sandbox Code Playgroud)
通常,日期时间格式存储在资源文件中,因为这有助于应用程序的国际化。
您可以从资源文件中选取格式并使用ToString(DATE_FORMAT)
在你的情况下,你可能想使用
dateTimePicker.SelectedDate.ToString("dd-MMM-yyyy");
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
65835 次 |
最近记录: |