【WPF】WPF 4.0 DatePicker 快速錄入

來源:互聯網
上載者:User

先發表在棒棒牛了,轉過來吧。

傳送門: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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.