// Keyboard Events void OnPreviewKeyDown(object sender, KeyEventArgs e) { var popup = VisualHelpers.FindAncester <PopupPanel>((DependencyObject)sender); var cmd = GetPopupEscapeKeyCommand(popup); switch (e.Key) { case Key.Escape: if (cmd != null && cmd.CanExecute(null)) { cmd.Execute(null); e.Handled = true; } else { // By default the Escape Key closes the popup when pressed var expression = GetBindingExpression(IsPopupVisibleProperty); if (expression != null) { var dataType = expression.DataItem.GetType(); dataType.GetProperties().Single(x => x.Name == expression.ParentBinding.Path.Path) .SetValue(expression.DataItem, false, null); } } break; case Key.Enter: // Don't want to run Enter command if focus is in a TextBox with AcceptsReturn = True if ( !(e.KeyboardDevice.FocusedElement is TextBox && ((TextBox)e.KeyboardDevice.FocusedElement).AcceptsReturn) && cmd != null && cmd.CanExecute(null)) { cmd.Execute(null); e.Handled = true; } break; } }
static object CoercePopupParent(DependencyObject obj, object value) { // If PopupParent is null, return the Window object return(value ?? VisualHelpers.FindAncester <Window>(obj)); }