先發表在棒棒牛了,轉過來吧。
傳送門:http://www.bbniu.com/forum/viewthread.php?tid=752&page=1&extra=#pid6692
WPF 4.0的DatePicker在通過鍵盤錄入日期的時候是非常讓人鬱悶的。必須按照日期的格式來完整輸入
例如,比如輸入“2010/10/10”才能識別。而實際上在一些要求快速錄入的場合,使用者更希望直接敲20101010就行了。
遺憾的是,DatePicker沒有一個屬性可以設定說錄入的格式是yyyyMMdd這種的。
實際上,仔細看一下DatePicker控制項,它有一個DateValidationError事件,當輸入的文本無法識別為日期時,就會觸發該事件。我們可以利用這個事件來做一些事情。
為了方便使用,我們可以封裝一個附加屬性,在需要快速錄入的地方Attach一下就好了。
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);
}
這樣,我們就給一個DatePickerHelper類型註冊了一個附加屬性,叫做EnableFastInput。
在這個屬性的PropertyChanged事件處理函數中,我們監聽DatePicker的DateValidationError事件
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;
}
}
}
在事件處理中,我們嘗試著解析文本,並且設定日期:
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;
}
}
}
在Xaml中使用時:
<DatePicker l:DatePickerHelper.EnabledFastInput="True"/>
這樣,DatePicker就支援直接輸入yyyyMMdd格式的日期了。
當然,這裡的日期格式是寫死的,可以考慮封裝成另外一個DatePickerHelper.InputDateFormat屬性之類的,更加靈活
【】
【代碼】
/Files/RMay/WpfDatePicker.zip