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;
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.
【]
Original (with source code): http://www.cnblogs.com/RMay/archive/2010/05/27/1745636.html