How to change format (e.g. dd/MMM/yyyy) of DateTimePicker in WPF application

Rajendra picture Rajendra · Mar 13, 2009 · Viewed 68.7k times · Source

I want to Change the Format of date selected in DateTimePicker in WPF Application

Answer

Fernando García picture Fernando García · Dec 10, 2010

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>

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.