【WPF】日历中拓展添加今天和清空按钮(菜鸟教程)

在xaml中标签上面添加如下代码
    
        

    


2.在MainWindow.xaml.cs中添加如下代码(粘贴后会有错误,根据修补程序的提示添加相应using即可)
    public class UserDatePicker : DatePicker
    {

        //日期文本框
        public DatePickerTextBox textBox;
        private Popup popup;
        //今天
        private TextBlock goToday;
        //清空
        private TextBlock goClear;

        #region 重载初始化
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            textBox = this.GetTemplateChild("PART_TextBox") as DatePickerTextBox;
            popup = this.GetTemplateChild("PART_Popup") as Popup;


            System.Windows.Controls.Calendar calendar = popup.Child as System.Windows.Controls.Calendar;
            calendar.Style = AlternativeCalendarStyle;
            calendar.ApplyTemplate();

            goToday = calendar.Template.FindName("PART_GoToday", calendar) as TextBlock;
            goClear = calendar.Template.FindName("PART_GoClear", calendar) as TextBlock;


            goToday.MouseLeftButtonUp -= new MouseButtonEventHandler(goToday_MouseLeftButtonUp);
            goToday.MouseLeftButtonUp += new MouseButtonEventHandler(goToday_MouseLeftButtonUp);

            goClear.MouseLeftButtonUp -= new MouseButtonEventHandler(goClear_MouseLeftButtonUp);
            goClear.MouseLeftButtonUp += new MouseButtonEventHandler(goClear_MouseLeftButtonUp);


            this.SelectedDateFormat = DatePickerFormat.Short;//格式转换:xxxx年xx月xx日->xxxx/xx/xx

        }
        #endregion

        /// 
        /// AlternativeCalendarStyle Dependency Property
        /// 
        public static readonly DependencyProperty AlternativeCalendarStyleProperty =
            DependencyProperty.Register("AlternativeCalendarStyle", typeof(Style), typeof(UserDatePicker),
                new FrameworkPropertyMetadata((Style)null,
                    null));


        public Style AlternativeCalendarStyle
        {
            get { return (Style)GetValue(AlternativeCalendarStyleProperty); }
            set { SetValue(AlternativeCalendarStyleProperty, value); }
        }

        #region 今天
        private void goToday_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            this.SelectedDate = DateTime.Now;
            popup.IsOpen = false;//关闭日历
        }
        #endregion

        #region 清空
        private void goClear_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            this.SelectedDate = null;
            popup.IsOpen = false;
        }
        #endregion
    }

3.在xaml中标签中添加如下代码(有时VS会提示不存在UserDatePicker,代码是没问题的,删掉下面的代码后启动一下再把下面的代码粘上就好了)

大功告成!!!

使用SelectedDateChanged属性时改成DatePicker.SelectedDateChanged="XXX"就可以了!
使用Name属性时改成x:Name就可以了!

运行截图:
【WPF】日历中拓展添加今天和清空按钮(菜鸟教程)_第1张图片

你可能感兴趣的:(【WPF】日历中拓展添加今天和清空按钮(菜鸟教程))