此代码使日历的背景为橙色,但不会将DisplayMode默认为Decade。有人知道为什么吗?如何将其默认为“十年”?
<DatePicker SelectedDate="{Binding TheDate}">
<DatePicker.CalendarStyle>
<Style TargetType="Calendar">
<Setter Property="DisplayMode" Value="Decade"/>
<Setter Property="Background" Value="Orange"/>
</Style>
</DatePicker.CalendarStyle>
</DatePicker>
答案 0 :(得分:4)
当弹出窗口打开时,DatePicker控件将CalendarMode显式设置为month,这将覆盖样式中的值。来自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());
}
我认为您无法在XAML中覆盖它,因为它显式设置了一个值。您可以添加一个处理程序CalendarOpened="DatePicker_CalendarOpened"
并通过执行以下操作将其设置为后面的代码中的Decade:
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;
}
}
}
(我尝试使用3.5中的WPF Toolkit DatePicker,所以我不保证它在4.0中有效。)
答案 1 :(得分:0)
Quartermeister的答案似乎是最干净的方法。但这对我没有用。 datepicker.Template.FindName始终返回null。所以我在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;
}
}