一、問題與修改
在上一篇文章中,出現了一個BUG,設置DatePicer控件輸入只讀,並非是真真的只讀,仍可以進行刪除,這與只讀的概念相違背了,利用TextBox的IsReadOnly屬性可以實現這一要求,不需要自己去定義只讀!
二、新的需求
在很多需求中,只需要選擇年,或者是只需要選擇月。在界面中,很多程序往往只使用ComboBox來實現這一需求。但是DatePicker完全能夠實現,大家都知道DatePicer控件使用了一個隱藏的 Calendar控件!手動更改CalendarMode屬性完全可以實現!因此,在DatePicker控件中,添加屬性DateMode屬性,繼承自CalendarMode,通過改變DateMode屬性來實現效果!
同時,要用到擴展方法(在本例中方法名:public static IEnumerable<DependencyObject> Descendents(this DependencyObject root)){})!它是一個靜態類中的一個靜態方法,通過此方法在DependencyObject類型中添加Descendents。在本例中的目的是爲了找到Calendar控件!具體如何使用,請查找相關的資料了!
二、代碼
public static class ControlsHelper
{
/// <summary>
/// 擴展DependencyObject Descendents方法,遞歸找到制定的控件
/// </summary>
/// <param name="root"></param>
/// <returns></returns>
public static IEnumerable<DependencyObject> Descendents(this DependencyObject root)
{
int count = VisualTreeHelper.GetChildrenCount(root);
for (int i = 0; i < count; i++)
{
var child = VisualTreeHelper.GetChild(root, i);
yield return child;
foreach (var descendent in Descendents(child))
yield return descendent;
}
}
}
public class DatePickerEx : DatePicker
{
#region 私有字段
DatePickerTextBox CurrentTextBox;//DatePicker的文本框控件
Popup CurrentPopup;//DatePicker控件的TempPart
Calendar CurrentCalendar;//日曆控件
Button CurrentButon;//DatePicker的Button控件
string DateFormat;//定義時間顯示格式
string _InputText;
public static readonly DependencyProperty IsReadOnlyProperty = DependencyProperty.Register("IsReadOnly", typeof(bool), typeof(DatePickerEx), new PropertyMetadata(false));
//public static readonly DependencyProperty InputTextProperty = DependencyProperty.Register("InputText", typeof(String), typeof(DatePickerEx), new PropertyMetadata("", InputTextChanged));
public static readonly DependencyProperty DateModeProperty = DependencyProperty.Register("DateMode", typeof(CalendarMode), typeof(DatePickerEx), new PropertyMetadata(CalendarMode.Month, DateModeChanged));
#endregion
#region 屬性
/// <summary>
/// 得到手動輸入的值
/// </summary>
public string InputText
{
//get { return (string)GetValue(InputTextProperty); }
//set { SetValue(InputTextProperty, value); }
get { return _InputText == null ? "" : _InputText; }
private set { _InputText = value; }
}
/// <summary>
/// 啓用和關閉手動輸入
/// </summary>
public bool IsReadOnly
{
get { return (bool)GetValue(IsReadOnlyProperty); }
set { SetValue(IsReadOnlyProperty, value); }
}
///// <summary>
/// 輸入時間類型
/// </summary>
public CalendarMode DateMode
{
get { return (CalendarMode)GetValue(DateModeProperty); }
set { SetValue(DateModeProperty, value); }
}
#endregion
#region 重寫方法及事件
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
this.CurrentTextBox = GetTemplateChild("TextBox") as DatePickerTextBox;
this.CurrentPopup = GetTemplateChild("Popup") as Popup;
this.CurrentButon = GetTemplateChild("Button") as Button;
#region 註冊及綁定事件
if (null != this.CurrentTextBox)
{
//this.CurrentTextBox.BorderThickness = new Thickness(1);
//this.CurrentButon.Margin = new Thickness(-25, 0, 0, 0);
this.SetTextMode(this.CurrentTextBox);
this.CurrentTextBox.IsReadOnly = this.IsReadOnly;
this.CurrentTextBox.TextChanged += ((sender, e) =>
{
if (this.IsReadOnly)
this.CurrentTextBox.Text = this.SelectedDate.HasValue ? this.SelectedDate.Value.ToString(this.DateFormat) : "";
else
{
if (this.CurrentTextBox.Text.Trim().Length >= this.DateFormat.Length)
{
DateTime timeTemp;
if (DateTime.TryParse(this.CurrentTextBox.Text.Trim(), out timeTemp))
this.CurrentTextBox.Text = timeTemp.ToString(this.DateFormat);
}
this.InputText = this.CurrentTextBox.Text;
}
SetTextMode(this.CurrentTextBox);
});
}
this.CalendarClosed += new RoutedEventHandler(DatePickerEx_CalendarClosed);
if (this.DateMode == CalendarMode.Month)
return;
if (null != this.CurrentPopup)
//利用擴展方法找到Calendar控件
this.CurrentCalendar = this.CurrentPopup.Child.Descendents().OfType<Calendar>().FirstOrDefault();
if (null != this.CurrentButon)
this.CurrentButon.Click += ((sender, e) =>
{
this.CurrentPopup.IsOpen = true;
});
if (null != this.CurrentCalendar)
{
this.CurrentCalendar.IsTodayHighlighted = true;
this.CurrentCalendar.DisplayModeChanged += new
EventHandler<CalendarModeChangedEventArgs>(CurrentCalendar_DisplayModeChanged);
this.CurrentCalendar.DisplayMode = this.DateMode;
this.CurrentCalendar.LostMouseCapture += ((sender, e) =>
{
this.SelectedDate = this.DisplayDate;
});
}
#endregion
}
void CurrentCalendar_DisplayModeChanged(object sender, CalendarModeChangedEventArgs e)
{
this.CurrentCalendar.DisplayModeChanged -= CurrentCalendar_DisplayModeChanged;
this.CurrentCalendar.DisplayModeChanged += CurrentCalendar_DisplayModeChanged;
Calendar cal = (Calendar)sender;
//首次加載以及重新賦值DisplayMode Calendar視圖情況判斷
if (e.OldMode.Equals(CalendarMode.Year) && !e.NewMode.Equals(CalendarMode.Month))
cal.DisplayMode = e.NewMode;
else
cal.DisplayMode = this.DateMode;
//僅選擇月 Calendar關閉情況判斷
if (e.NewMode.Equals(CalendarMode.Month))
this.CurrentPopup.IsOpen = false;
//只選擇年。 Calendar 關閉情況判斷
if (this.DateMode == CalendarMode.Decade && e.NewMode == CalendarMode.Year && e.OldMode == this.DateMode)
this.CurrentPopup.IsOpen = false;
}
/// <summary>
/// 設置日期顯示格式
/// </summary>
/// <param name="tbx"></param>
protected void SetTextMode(DatePickerTextBox tbx)
{
if (null == tbx)
return;
switch (this.DateMode)
{
case CalendarMode.Year:
DateFormat = "yyyy-MM";
tbx.Watermark = "<yyyy-MM>";
break;
case CalendarMode.Decade:
DateFormat = "yyyy";
tbx.Watermark = "<yyyy>";
break;
default:
DateFormat = "yyyy-MM-dd";
break;
}
tbx.UpdateLayout();
}
#endregion
//protected override
#region 自定義事件
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
if (!this.IsReadOnly)
this.InputText = this.CurrentTextBox.Text;
}
protected virtual void DatePickerEx_CalendarClosed(object sender, RoutedEventArgs e)
{
if (null != this.SelectedDate)
this.Text = this.SelectedDate.Value.ToString(this.DateFormat);
this.InputText = this.Text;
}
//protected static void InputTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
//{
// DatePickerEx sender = d as DatePickerEx;
// if (null != sender.CurrentTextBox)
// sender.CurrentTextBox.Text = e.NewValue.ToString();
//}
protected static void DateModeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DatePickerEx sender = d as DatePickerEx;
if (null != sender.CurrentCalendar)
sender.CurrentCalendar.DisplayMode = (CalendarMode)e.NewValue;
sender.SetTextMode(sender.CurrentTextBox);
}
#endregion
}