windows store app date picker null date

感情迁移 提交于 2019-12-24 13:47:31

问题


i need datepicker in window store app , windows 8, but i am not able to find any control, so i used this :

jasonmitchell / WinRT-XAML-DatePicker

https://github.com/jasonmitchell/WinRT-XAML-DatePicker/blob/master/Samples/WinRTDatePicker.Samples.sln

but my problem is , by default it shows today date, that i don't want, i don't want to show any date, if user did not apply any date

if anybody have idea to working with date-picker in windows metro application, that will be great,

i know windows 8.1 have that control but i cannot moved to windows 8.1 now!

code example :

  <WinRTDatePicker:DatePicker IsEnabled="True" x:Name="dtActualFinishDate" Width="370"/>

    i want to set value if 

    if (Booking.ActualToDteTme.HasValue)
                {
                    dtActualFinishDate.SelectedDate = Booking.ActualToDteTme.Value;
    }

so if ActualToDteTme have any value, i want to apply otherwise, i need to keep datepicker is as blank,

for now it is show as currect date, and when i click on Update, it updated current date !! that's not right behaviour!!

Thanks


回答1:


I am giving you updated DatePicker & SelectedDateChangedEventArgs class. Use these classes instead from Github. I have added default "month", "date", "year" placeholder text. Default value will be null & if anyone selects placeholder text then also it will be null.

using System;
using System.Collections.ObjectModel;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;

namespace WinRTDatePicker
{
    [TemplatePart(Name = "_DayOptions", Type = typeof(ComboBox))]
    [TemplatePart(Name = "_MonthOptions", Type = typeof(ComboBox))]
    [TemplatePart(Name = "_YearOptions", Type = typeof(ComboBox))]
    public sealed class DatePicker : Control
    {
        public static readonly DependencyProperty SelectedDateProperty = DependencyProperty.Register("SelectedDate", typeof(DateTime?), typeof(DatePicker), new PropertyMetadata(default(DateTime?), SelectedDateChangedCallback));
        public static readonly DependencyProperty DayOptionFormatProperty = DependencyProperty.Register("DayOptionFormat", typeof(string), typeof(DatePicker), new PropertyMetadata(default(string)));
        public static readonly DependencyProperty MonthOptionFormatProperty = DependencyProperty.Register("MonthOptionFormat", typeof(string), typeof(DatePicker), new PropertyMetadata(default(string)));

        public event EventHandler<SelectedDateChangedEventArgs> SelectedDateChanged; 

        private readonly ObservableCollection<string> daysInRange = new ObservableCollection<string>();
        private readonly ObservableCollection<string> monthsInRange = new ObservableCollection<string>();
        private readonly ObservableCollection<string> yearsInRange = new ObservableCollection<string>();

        public DatePicker()
        {
            DefaultStyleKey = typeof(DatePicker);

            //SelectedDate = DateTime.Today;
            DayOptionFormat = "dd dddd";
            MonthOptionFormat = "MMMM";
        }

        protected override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            monthsInRange.Clear();
            monthsInRange.Add("Month");
            for (int i = 1; i <= 12; i++)
            {
                DateTime monthStart = new DateTime(DateTime.Now.Year, i, 1);
                monthsInRange.Add(monthStart.ToString(MonthOptionFormat));
            }

            CreateBindings();
            SetSelectedDate(SelectedDate);

            DayOptions.SelectionChanged += DayOptionsOnSelectionChanged;
            MonthOptions.SelectionChanged += MonthOptionsOnSelectionChanged;
            YearOptions.SelectionChanged += YearOptionsOnSelectionChanged;
        }

        private void SetSelectedDate(DateTime? newSelectedDate)
        {
            if (DayOptions != null && MonthOptions != null && YearOptions != null)
            {
                var TempNewSelectedDate = newSelectedDate;
                if (newSelectedDate == null)
                {
                    newSelectedDate = DateTime.Today;
                }
                daysInRange.Clear();
                yearsInRange.Clear();

                daysInRange.Add("Date");
                for (int i = 1; i <= DateTime.DaysInMonth(newSelectedDate.Value.Year, newSelectedDate.Value.Month); i++)
                {
                    DateTime date = new DateTime(newSelectedDate.Value.Year, newSelectedDate.Value.Month, i);
                    daysInRange.Add(date.ToString(DayOptionFormat));
                }

                int minYear = newSelectedDate.Value.Year - 10;
                int maxYear = newSelectedDate.Value.Year + 10;

                yearsInRange.Add("Year");
                for (int i = minYear; i <= maxYear; i++)
                {
                    yearsInRange.Add(i.ToString());
                }

                if (TempNewSelectedDate != null)
                {
                    DayOptions.SelectedIndex = newSelectedDate.Value.Day;
                    MonthOptions.SelectedIndex = newSelectedDate.Value.Month;
                    YearOptions.SelectedItem = newSelectedDate.Value.Year.ToString();
                }

                else
                {
                    DayOptions.SelectedIndex = 0;
                    MonthOptions.SelectedIndex = 0;
                    YearOptions.SelectedIndex = 0;
                }
            }
        }

        private void CreateBindings()
        {
            Binding dayOptionsBinding = new Binding { Source = daysInRange, Mode = BindingMode.OneWay };
            DayOptions.SetBinding(ItemsControl.ItemsSourceProperty, dayOptionsBinding);

            Binding monthOptionsBinding = new Binding { Source = monthsInRange, Mode = BindingMode.OneWay };
            MonthOptions.SetBinding(ItemsControl.ItemsSourceProperty, monthOptionsBinding);

            Binding yearOptionsBinding = new Binding { Source = yearsInRange, Mode = BindingMode.OneWay };
            YearOptions.SetBinding(ItemsControl.ItemsSourceProperty, yearOptionsBinding);
        }

        private void UpdateSelectedDateFromInputs()
        {
            if (YearOptions.SelectedIndex > 0 && MonthOptions.SelectedIndex > 0 && DayOptions.SelectedIndex > 0)
            {
                int year = int.Parse(YearOptions.SelectedValue.ToString());
                int month = MonthOptions.SelectedIndex;
                int day = DayOptions.SelectedIndex;

                int maxDaysInMonth = DateTime.DaysInMonth(year, month);
                if (day > maxDaysInMonth)
                {
                    day = maxDaysInMonth;
                    DayOptions.SelectedIndex = maxDaysInMonth - 1;
                }

                if (month == 0)
                    month = 1;

                if (day == 0)
                    day = 1;

                SelectedDate = new DateTime(year, month, day);
            }
            else if (YearOptions.SelectedIndex == 0 && MonthOptions.SelectedIndex == 0 && DayOptions.SelectedIndex == 0)
            {
                SelectedDate = null;
            }
        }

        private void UpdateDayOptions()
        {
            if (SelectedDate != null)
            {
                int selectedDayIndex = DayOptions.SelectedIndex;
                int month = MonthOptions.SelectedIndex;

                if (month != 0)
                {
                    daysInRange.Clear();
                    daysInRange.Add("Date");
                    for (int i = 1; i <= DateTime.DaysInMonth(SelectedDate.Value.Year, month); i++)
                    {
                        DateTime date = new DateTime(SelectedDate.Value.Year, month, i);
                        daysInRange.Add(date.ToString(DayOptionFormat));
                    }

                    DayOptions.SelectedIndex = selectedDayIndex;  
                }
            }
        }

        private void DayOptionsOnSelectionChanged(object sender, SelectionChangedEventArgs selectionChangedEventArgs)
        {
            UpdateSelectedDateFromInputs();
        }

        private void MonthOptionsOnSelectionChanged(object sender, SelectionChangedEventArgs selectionChangedEventArgs)
        {
            UpdateSelectedDateFromInputs();
            UpdateDayOptions();
        }

        private void YearOptionsOnSelectionChanged(object sender, SelectionChangedEventArgs selectionChangedEventArgs)
        {
            UpdateSelectedDateFromInputs();
            UpdateDayOptions();
        }

        private static void SelectedDateChangedCallback(DependencyObject obj, DependencyPropertyChangedEventArgs args)
        {
            DateTime oldValue = args.OldValue != null ? (DateTime)args.OldValue : DateTime.Today.AddDays(-1);
            DateTime? newValue = (DateTime?)args.NewValue;

            if (newValue != oldValue)
            {
                DatePicker datePicker = (DatePicker)obj;
                datePicker.SetSelectedDate(newValue);

                if (datePicker.SelectedDateChanged != null)
                    datePicker.SelectedDateChanged(datePicker, new SelectedDateChangedEventArgs(newValue));
            }
        }

        public DateTime? SelectedDate
        {
            get { return (DateTime?)GetValue(SelectedDateProperty); }
            set { SetValue(SelectedDateProperty, value); }
        }

        public string DayOptionFormat
        {
            get { return (string)GetValue(DayOptionFormatProperty); }
            set { SetValue(DayOptionFormatProperty, value); }
        }

        public string MonthOptionFormat
        {
            get { return (string)GetValue(MonthOptionFormatProperty); }
            set { SetValue(MonthOptionFormatProperty, value); }
        }

        private ComboBox DayOptions
        {
            get { return (ComboBox)GetTemplateChild("_DayOptions"); }
        }

        private ComboBox MonthOptions
        {
            get { return (ComboBox)GetTemplateChild("_MonthOptions"); }
        }

        private ComboBox YearOptions
        {
            get { return (ComboBox)GetTemplateChild("_YearOptions"); }
        }
    }
}

using System;

namespace WinRTDatePicker
{
    public class SelectedDateChangedEventArgs : EventArgs
    {
        private readonly DateTime? newDate;

        public SelectedDateChangedEventArgs(DateTime? newDate)
        {
            this.newDate = newDate;
        }

        public DateTime? NewDate
        {
            get { return newDate; }
        }
    }
}



回答2:


For the binding to work you should change SelectedDateProperty to

public static readonly DependencyProperty SelectedDateProperty = 
    DependencyProperty.Register("SelectedDate",
                                typeof(object),
                                typeof(NullableDatePicker),
                                new PropertyMetadata(null, SelectedDateChangedCallback));

to avoid the error:

Error: Converter failed to convert value of type 'System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' to type 'Nullable`1';



来源:https://stackoverflow.com/questions/20535604/windows-store-app-date-picker-null-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!