private static void PopupCalendarLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
 {
     if (_popupCalControl != null &&
         !(e.NewFocus is CalendarDayButton) &&
         !(e.NewFocus is CalendarButton))
     {
         _popupCalControl.IsOpen = false;
         _popupCalControl        = null;
     }
 }
        private static void FrameworkElementGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            var frameworkElement = sender as FrameworkElement;

            if (frameworkElement != null)
            {
                if (_popupCalControl == null)
                {
                    _popupCalControl = new CalandarPopupControl();

                    _popupCalControl.AddHandler(UIElement.LostKeyboardFocusEvent,
                                                new KeyboardFocusChangedEventHandler(PopupCalendarLostKeyboardFocus));
                }

                _popupCalControl.TargetTextBox = GetTargetTextBox(frameworkElement);
                _popupCalControl.IsOpen        = true;
            }
        }
        private static void FrameworkElementLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            var frameworkElement = sender as FrameworkElement;

            if (frameworkElement != null)
            {
                if (_popupCalControl != null &&
                    !(e.NewFocus is CalendarDayButton) &&
                    !(e.NewFocus is CalendarButton))
                {
                    // Retrieves the setting for the State property
                    SetState(frameworkElement, _popupCalControl.State);

                    _popupCalControl.IsOpen = false;
                    _popupCalControl        = null;
                }
            }
        }
        private static void OnPlacementTargetChanged(DependencyObject element, DependencyPropertyChangedEventArgs e)
        {
            var frameworkElement = element as FrameworkElement;

            if (_popupCalControl == null)
            {
                _popupCalControl = new CalandarPopupControl();

                _popupCalControl.AddHandler(UIElement.LostKeyboardFocusEvent,
                                            new KeyboardFocusChangedEventHandler(PopupCalendarLostKeyboardFocus));
            }
            if (frameworkElement != null &&
                _popupCalControl != null)
            {
                _popupCalControl.TargetTextBox = GetTargetTextBox(frameworkElement);
                frameworkElement.AddHandler(UIElement.GotKeyboardFocusEvent,
                                            new KeyboardFocusChangedEventHandler(FrameworkElementGotKeyboardFocus),
                                            true);
                frameworkElement.AddHandler(UIElement.LostKeyboardFocusEvent,
                                            new KeyboardFocusChangedEventHandler(FrameworkElementLostKeyboardFocus));
            }
        }