I posted the post on Niu first. Turn it around.
Door: http://www.bbniu.com/forum/viewthread.php? Tid = 752 & page = 1 & extra = # pid6692
The DatePicker of WPF 4.0 is very depressing when entering a date through the keyboard. Complete input must be in the Date Format
For example, if you enter "2010/10/10. In fact, in some scenarios where fast input is required, users prefer to press 20101010 directly.
Unfortunately, no DatePicker attribute can be set to indicate that the input format is yyyyMMdd.
In fact, take a closer look at the DatePicker control, which has a DateValidationError event. This event is triggered when the input text cannot be recognized as a date. We can use this event to do something.
For ease of use, we can encapsulate an additional attribute and Attach it to the desired location.
Public static readonly DependencyProperty EnableFastInputProperty =
DependencyProperty. RegisterAttached ("EnableFastInput", typeof (bool), typeof (DatePickerHelper ),
New FrameworkPropertyMetadata (bool) false,
New PropertyChangedCallback (OnEnableFastInputChanged )));
Public static bool GetEnableFastInput (DependencyObject d)
{
Return (bool) d. GetValue (EnableFastInputProperty );
}
Public static void SetEnableFastInput (DependencyObject d, bool value)
{
D. SetValue (EnableFastInputProperty, value );
}
In this way, an additional attribute is registered for a DatePickerHelper type, called EnableFastInput.
In the PropertyChanged event processing function of this attribute, we listen to the DateValidationError event of DatePicker.
Private static void OnEnableFastInputChanged (DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Var datePicker = d as DatePicker;
If (datePicker! = Null)
{
If (bool) e. NewValue)
{
DatePicker. DateValidationError + = DatePickerOnDateValidationError;
}
Else
{
DatePicker. DateValidationError-= DatePickerOnDateValidationError;
}
}
}
In event processing, we try to parse the text and set the date:
Private static void DatePickerOnDateValidationError (object sender, DatePickerDateValidationErrorEventArgs e)
{
Var datePicker = sender as DatePicker;
If (datePicker! = Null)
{
Var text = e. Text;
DateTime dateTime;
If (DateTime. TryParseExact (text, "yyyyMMdd", CultureInfo. CurrentUICulture, DateTimeStyles. None, out dateTime ))
{
DatePicker. SelectedDate = dateTime;
}
}
}
When used in Xaml:
<DatePicker l: DatePickerHelper. EnabledFastInput = "True"/>
In this way, DatePicker supports entering the date in yyyyMMdd format directly.
Of course, the date format here is written to death. You can consider encapsulating it into another DatePickerHelper. InputDateFormat attribute, which is more flexible.
【]
[Code]
/Files/RMay/WpfDatePicker.zip