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

后端 未结 9 2169
春和景丽
春和景丽 2020-12-14 03:52

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

9条回答
  •  借酒劲吻你
    2020-12-14 04:02

    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:

    
        
    
    

    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.

提交回复
热议问题