WPF 4 - DatePicker - How to set DisplayMode to Decade?

為{幸葍}努か 提交于 2021-02-10 16:47:16

问题


This code makes the background of the calendar orange, but it does not default the DisplayMode to Decade. Does anybody know why? What can I do to default it to "Decade"?

<DatePicker SelectedDate="{Binding TheDate}">
    <DatePicker.CalendarStyle>
        <Style TargetType="Calendar">
            <Setter Property="DisplayMode" Value="Decade"/>
            <Setter Property="Background" Value="Orange"/>
        </Style>
    </DatePicker.CalendarStyle>
</DatePicker>

回答1:


The DatePicker control sets CalendarMode to month explicitly when the popup opens, which overrides the value from your style. From Reflector:

private void PopUp_Opened(object sender, EventArgs e)
{
    if (!this.IsDropDownOpen)
    {
        this.IsDropDownOpen = true;
    }
    if (this._calendar != null)
    {
        this._calendar.DisplayMode = CalendarMode.Month;
        this._calendar.MoveFocus(
            new TraversalRequest(FocusNavigationDirection.First));
    }
    this.OnCalendarOpened(new RoutedEventArgs());
}

I don't think you will be able to override that in XAML because it is setting a value explicitly. You could add a handler CalendarOpened="DatePicker_CalendarOpened" and set it back to Decade in the code behind by doing something like this:

private void DatePicker_CalendarOpened(object sender, RoutedEventArgs e)
{
    var datepicker = sender as DatePicker;
    if (datepicker != null)
    {
        var popup = datepicker.Template.FindName(
            "PART_Popup", datepicker) as Popup;
        if (popup != null && popup.Child is Calendar)
        {
            ((Calendar)popup.Child).DisplayMode = CalendarMode.Decade;
        }
    }
}

(I tried this with the WPF Toolkit DatePicker in 3.5, so I don't promise it works in 4.0.)




回答2:


Quartermeister's answer seems to be the cleanest way. But it didn't work for me. The datepicker.Template.FindName always returned null. So I did this slightly differently in 4.6.1.

    private void DatePicker_CalendarOpened(object sender, RoutedEventArgs e)
    {
        DatePicker datepicker = (DatePicker)sender;
        Popup popup = (Popup)datepicker.Template.FindName("PART_Popup", datepicker);
        if (popup != null)
        {
            System.Windows.Controls.Calendar cal = (System.Windows.Controls.Calendar)popup.Child;
            if (cal != null) cal.DisplayMode = System.Windows.Controls.CalendarMode.Decade;
        }
    }


来源:https://stackoverflow.com/questions/3569713/wpf-4-datepicker-how-to-set-displaymode-to-decade

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!