我要更改日期在WPF应用程序中的DateTimePicker选择的格式
I want to Change the Format of date selected in DateTimePicker in WPF Application
我在这个问题rencetly处理。我发现执行此自定义格式一个简单的方法,我希望这可以帮助您。你需要做的第一件事情就是将特定的风格,以你目前的DatePicker就这样,在你的XAML:
I was handling with this issue rencetly. I found a simple way to perform this custom format and I hope that this help you. First thing that you need to do is apply a specific style to your current DatePicker just like this, in your XAML:
<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>
正如你可以在这个部分看到,存在一个名为DateTimeFormatter当时作出具有约束力的PART_TextBox的Text属性转换器。该转换器接收,包括您的自定义格式的converterparameter。最后,我们添加了code在C#中的DateTimeFormatter转换器。
As you can notice at this part, exist a Converter called DateTimeFormatter at the time to make binding to the Text property of the "PART_TextBox". This converter receives the converterparameter that includes your custom format. Finally we add the code in C# for the DateTimeFormatter converter.
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;
}
}
}
我希望这对您有所帮助。请让我知道的任何问题或建议的改善。
I hope this help to you. Please let me know for any issue or suggesting for improve.
下一篇:编译时间反射在C#反射、时间