我派生了 DatePicker 类以支持额外的 DateMode 属性,该属性将允许用户仅按照 DateMode(日、月、年)使用控件。因此,如果 DateMode 设置为 Year,则控件将无法进一步向下钻取以查看一年中的月份,然后再进一步查看月份中的几天。控制工作良好,但有一个问题。虽然我已经在 DatePicker 模板中的“PART_TextBox”控件上应用了字符串格式,这将根据 DateMode 更改格式,但一旦 DatePicker 控件失去焦点,格式就会丢失。以下是我派生的 DatePicker 控件代码:
public class MyDatePicker : DatePicker
{
public string DateMode
{
get { return (string)GetValue(DateModeProperty); }
set { SetValue(DateModeProperty, value); }
}
// Using a DependencyProperty as the backing store for DateMode. This enables animation, styling, binding, etc...
public static readonly DependencyProperty DateModeProperty =
DependencyProperty.Register("DateMode", typeof(string), typeof(MyDatePicker), new UIPropertyMetadata("Day"));
protected override void OnCalendarOpened(RoutedEventArgs e)
{
var popup = this.Template.FindName("PART_Popup", this) as Popup;
var tb = this.Template.FindName("PART_TextBox", this) as TextBox;
if (popup != null && popup.Child is System.Windows.Controls.Calendar)
{
if (DateMode == "Year")
((System.Windows.Controls.Calendar)popup.Child).DisplayMode = CalendarMode.Decade;
else if (DateMode == "Month")
((System.Windows.Controls.Calendar)popup.Child).DisplayMode = CalendarMode.Year;
else if (DateMode == "Day")
((System.Windows.Controls.Calendar)popup.Child).DisplayMode = CalendarMode.Month;
}
((System.Windows.Controls.Calendar)popup.Child).DisplayModeChanged += new EventHandler<CalendarModeChangedEventArgs>(DatePickerCo_DisplayModeChanged);
}
protected override void OnCalendarClosed(RoutedEventArgs e)
{
base.OnCalendarClosed(e);
IsDropDownOpen = false;
var popup = this.Template.FindName("PART_Popup", this) as Popup;
((System.Windows.Controls.Calendar)popup.Child).DisplayModeChanged -= new EventHandler<CalendarModeChangedEventArgs>(DatePickerCo_DisplayModeChanged);
}
private void DatePickerCo_DisplayModeChanged(object sender, CalendarModeChangedEventArgs e)
{
var popup = this.Template.FindName("PART_Popup", this) as Popup;
var tb = this.Template.FindName("PART_TextBox", this) as TextBox;
if (popup != null && popup.Child is System.Windows.Controls.Calendar)
{
var _calendar = popup.Child as System.Windows.Controls.Calendar;
if (DateMode == "Month" && _calendar.DisplayMode == CalendarMode.Month)
{
if (IsDropDownOpen)
{
this.SelectedDate = _calendar.DisplayDate;
this.IsDropDownOpen = false;
_calendar.DisplayMode = CalendarMode.Year;
}
tb.Text = this.SelectedDate.Value.ToString("MMM yyyy");
}
else if (DateMode == "Year" && _calendar.DisplayMode == CalendarMode.Year)
{
if (IsDropDownOpen)
{
this.SelectedDate = _calendar.DisplayDate;
this.IsDropDownOpen = false;
_calendar.DisplayMode = CalendarMode.Decade;
}
tb.Text = this.SelectedDate.Value.ToString("yyyy");
}
}
}
}