Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
503 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...