How to get the selection from the custom DateTimePicker using SfPicker
This section explains how to get the selection from the DateTimePicker.
Refer to this Gettingstarted documentation, to create a simple SfPicker sample and configure it.
Step 1: Create a custom class with DateTimePicker that should be inherited from SfPicker.
public class DateTimePicker : SfPicker |
Step 2: Create the collection to be viewed for todaycollection with the object type.
public DateTimePicker(Context context) : base(context)
{
ObservableCollection<object> todaycollection = new ObservableCollection<object>();
//Select today dates
todaycollection.Add(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(DateTime.Now.Date.Month).Substring(0, 3));
if (DateTime.Now.Date.Day < 10)
{
todaycollection.Add("0" + DateTime.Now.Date.Day);
}
else
{
todaycollection.Add(DateTime.Now.Date.Day.ToString());
}
todaycollection.Add(DateTime.Now.Date.Year.ToString());
todaycollection.Add(DateTime.Now.Hour.ToString());
todaycollection.Add(DateTime.Now.Minute.ToString());
this.StartDate = todaycollection;
Months = new Dictionary<string, string>();
Date = new ObservableCollection<object>();
Day = new ObservableCollection<object>();
Month = new ObservableCollection<object>();
Year = new ObservableCollection<object>();
Hour = new ObservableCollection<object>();
Minute = new ObservableCollection<object>();
Headers = new ObservableCollection<string>();
Headers.Add("MONTH");
Headers.Add("DAY");
Headers.Add("YEAR");
Headers.Add("HOUR");
Headers.Add("MINUTE");
HeaderText = "SELECT A DATE & TIME";
PopulateDateCollection();
this.ItemsSource = Date;
this.ColumnHeaderText = Headers;
this.OnSelectionChanged += DateTimePicker_OnSelectionChanged;
this.OkButtonClicked += DateTimePicker_OkButtonClicked;
ShowFooter = true;
ShowHeader = true;
ShowColumnHeader = true;
}
Step 3: Updated the day value based on month and year values using the SelectionChangedEvent of SfPicker control. Since, the days of each month differs, we have to handle this collection.
private void DateTimePicker_OnSelectionChanged(object sender, SelectionChangedEventArgs e) //Updatedays method is used to alter the Date collection as per selection change in Month column(if feb is Selected day collection has value from 1 to 28) public void UpdateDays(ObservableCollection<object> Date, SelectionChangedEventArgs e) { |
Step 4: Get the Selection from the following method.
private string GetSelectedItems(ICollection collection) { string dates = string.Empty; int i = 0; foreach (var item in collection) { dates += item; dates += " "; i++; }
return dates; } |
Step 5: Display the date using the SelectionChangedEvent value.
private void DateTimePicker_OkButtonClicked(object sender, SelectionChangedEventArgs e) { var date = GetSelectedItems(e.NewValue as ICollection); Toast.MakeText(this.Context, date, ToastLength.Short).Show(); } |
You can find the sample in the following link.