WPF Toolkit DatePicker Month/Year Only

前端 未结 7 513
暗喜
暗喜 2020-12-02 23:45

I\'m using the Toolkit\'s Datepicker as above but I\'d like to restrict it to month and year selections only, as in this situation the users don\'t know or care about the ex

7条回答
  •  青春惊慌失措
    2020-12-03 00:11

    I want to provide an alternative solution that doesn't require a lot of code. You can bind to a DatePickers's CalendarOpened event. In that event you can set the display mode of the Calendar to Decade and add an event handler for the DisplayModeChanged event on the Calendar. Then in the DisplayModeChanged event handler you can close the calendar if the mode is month, and also set the SelectedDate to the current DisplayDate. This has worked well for my purposes

    XAML

    
    
        
    
    

    Then for the code behind

    private void DatePicker_Opened(object sender, RoutedEventArgs e)
    {
        DatePicker datepicker = (DatePicker)sender;
        Popup popup = (Popup)datepicker.Template.FindName("PART_Popup", datepicker);
        Calendar cal = (Calendar)popup.Child;
        cal.DisplayModeChanged += Calender_DisplayModeChanged;
        cal.DisplayMode = CalendarMode.Decade;
    }
    
    private void Calender_DisplayModeChanged(object sender, CalendarModeChangedEventArgs e)
    {
        Calendar calendar = (Calendar)sender;
        if (calendar.DisplayMode == CalendarMode.Month)
        {
            calendar.SelectedDate = calendar.DisplayDate;
            YearPicker.IsDropDownOpen = false;
        }
    }
    

    I hope this helps!

提交回复
热议问题