Category / Section
How to hook the Done and Cancel events of the SfDateSelector?
1 min read
When using the SfDatePicker, you cannot hook the Done and Cancel events of the SfDateSelector directly. You have to retrieve it manually and hook the events as follows.
Retrieving SfDateSelector
SfDateSelector is rendered only after the dropdown opens. So you have to manually retrieve the selector by using the VisualTreeHelper in a dropdown popup Opened event.
MainWindow.xaml
<sync:SfDatePicker x:Name="datePicker" Loaded="datePicker_Loaded"/>
MainWindow.xaml.cs
public sealed partial class MainPage : Page { Popup dropdownPopup; public MainPage() { this.InitializeComponent(); } public static IEnumerable<T> FindVisualChildrenOfType<T>(DependencyObject parent) where T : DependencyObject { List<T> foundChildren = new List<T>(); int childCount = VisualTreeHelper.GetChildrenCount(parent); for (int i = 0; i < childCount; i++) { var child = VisualTreeHelper.GetChild(parent, i); T childType = child as T; if (childType == null) { foreach (var other in FindVisualChildrenOfType<T>(child)) yield return other; } else { yield return (T)child; } } } private void datePicker_Loaded(object sender, RoutedEventArgs e) { if (datePicker != null) { foreach (Popup popup in FindVisualChildrenOfType<Popup>(datePicker)) { if (popup!=null && popup.Name == "PART_DropDown") { dropdownPopup = popup; dropdownPopup.Opened += dropdownpopup_Opened; } } } } private void dropdownpopup_Opened(object sender, object e) { if (dropdownPopup != null && dropdownPopup.Child != null && dropdownPopup.Child is Grid && (dropdownPopup.Child as Grid).Children.Count > 0) { SfDateSelector selector = null; foreach (var child in (dropdownPopup.Child as Grid).Children) { selector = child is SfDateSelector ? child as SfDateSelector : null; if (selector != null) break; } if (selector != null) { selector.Done += selector_Done; selector.Cancel += selector_Cancel; } } dropdownPopup.Opened += dropdownpopup_Opened } void selector_Cancel(object sender, RoutedEventArgs e) { } void selector_Done(object sender, RoutedEventArgs e) { } }