The DatePicker of WPF 4.0 is frustrating when it comes to typing dates through the keyboard. Must be fully entered according to the format of the date
For example, enter "2010/10/10" for identification. In fact, in some of the requirements of fast entry, the user would prefer to knock 20101010 directly on the line.
Unfortunately, DatePicker does not have an attribute that can be set to say that the format of the entry is YYYYMMDD this.
In fact, take a closer look at the DatePicker control, which has a datevalidationerror event that fires when the input text is not 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 in a place where fast entry is required.
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, we register an additional property for a datepickerhelper type called Enablefastinput.
In the PropertyChanged event handler for this property, we listen to the DatePicker datevalidationerror event
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 handling, 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 the direct input of the date in the YYYYMMDD format.
Of course, the date format here is written dead, you can consider encapsulation into another Datepickerhelper.inputdateformat property, and so on, more flexible
【】
Original (source code): http://www.cnblogs.com/RMay/archive/2010/05/27/1745636.html
WPF 4.0 DatePicker Fast Entry