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"?
<DatePicke开发者_Go百科r SelectedDate="{Binding TheDate}">
<DatePicker.CalendarStyle>
<Style TargetType="Calendar">
<Setter Property="DisplayMode" Value="Decade"/>
<Setter Property="Background" Value="Orange"/>
</Style>
</DatePicker.CalendarStyle>
</DatePicker>
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.)
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;
}
}
精彩评论