private void RestorePreviousFocus() { if (this.IsKeyboardFocusWithin) { Keyboard.Focus(null); FocusManager.SetFocusedElement(this, null); } DependencyObject parent = this.Parent; if (parent != null) { DependencyObject focusScope = FocusManager.GetFocusScope(parent); if (focusScope != null) { IInputElement focusedElement = FocusManager.GetFocusedElement(focusScope); if (this.ElementIsWithin(focusedElement)) { FocusManager.SetFocusedElement(focusScope, null); } } } }
private void MainPage_GotFocus(object sender, RoutedEventArgs e) { FrameworkElement focus = FocusManager.GetFocusedElement() as FrameworkElement; if (focus != null) { if (focus.GetType() == typeof(GridViewItem)) { control = ((focus.FindDescendantByName("TemplateRoot")) as Grid); if (control != null) { try { SoundItemAnimations.ItemScaleUp(control, 1.1f); } catch { } } } focus.LostFocus += (f, g) => { if (focus.GetType() == typeof(GridViewItem)) { control = ((focus.FindDescendantByName("TemplateRoot")) as Grid); if (control != null) { try { SoundItemAnimations.ItemScaleNormal(control); } catch { } } } }; } }
protected override void OnCharacterReceived(CharacterReceivedRoutedEventArgs e) { if (ParentShellPageInstance != null) { if (ParentShellPageInstance.CurrentPageType == typeof(GridViewBrowser) && !IsRenamingItem) { // Don't block the various uses of enter key (key 13) var focusedElement = FocusManager.GetFocusedElement() as FrameworkElement; if (e.Character == (char)13 || focusedElement is Button || focusedElement is TextBox || focusedElement is PasswordBox || Interaction.FindParent <ContentDialog>(focusedElement) != null) { return; } base.OnCharacterReceived(e); FileList.Focus(FocusState.Keyboard); } } }
public void FocusNextTextBox(bool reverse = false) { var textBoxes = VisualTreeHelperEx.GetChildren(mUnitPriceItemsControl, true) .OfType <TextBox>() .Where(textbox => !textbox.IsReadOnly && textbox.IsEnabled); if (reverse) { textBoxes = textBoxes.Reverse(); } TextBox first = null; var lastTextBoxIsFocused = false; var focusChanged = false; foreach (var textBox in textBoxes) { if (first == null) { first = textBox; } if (lastTextBoxIsFocused) { textBox.Focus(); focusChanged = true; break; } else { lastTextBoxIsFocused = ReferenceEquals(FocusManager.GetFocusedElement(), textBox); } } if (!focusChanged && first != null) { first.Focus(); } }
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e) { //Trace the event for debug purposes Utils.Trace("Navigated From SecondPage"); //Remove focused element from previous time if any if (State.ContainsKey("FocusedElement")) { State.Remove("FocusedElement"); } //If some input control is in focus, save it to the page state object obj = FocusManager.GetFocusedElement(); if (null != obj) { string focusedControl = (obj as FrameworkElement).Name; State.Add("FocusedElement", focusedControl); } base.OnNavigatedFrom(e); }
void ViewBase_KeyUp(object sender, System.Windows.Input.KeyEventArgs e) { if (e.Key == Key.F1) { var viewModel = this.DataContext as ViewModelBase; if (viewModel != null) { var helpTopic = "Index"; var focusedElement = FocusManager.GetFocusedElement(this) as FrameworkElement; if (focusedElement != null) { var keyword = ContextHelp.GetKeyword(focusedElement); if (!String.IsNullOrWhiteSpace(keyword)) { helpTopic = keyword; } } viewModel.HelpCommand.Execute(helpTopic); } } }
/// <summary> /// F1 リボン マスタ検索 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public override void OnF1Key(object sender, KeyEventArgs e) { try { var ctl = FocusManager.GetFocusedElement(this); var uctext = ViewBaseCommon.FindVisualParent <M01_TOK_TextBox>(ctl as UIElement); if (uctext != null) { uctext.OpenSearchWindow(this); } else { ViewBaseCommon.CallMasterSearch(this, this.MasterMaintenanceWindowList); } } catch (Exception ex) { appLog.Error("検索画面起動エラー", ex); ErrorMessage = "システムエラーです。サポートへご連絡ください。"; } }
private void Timer_Tick(object sender, object e) { // Update the type, name, and content shown in the popup's text. object focusedElement = FocusManager.GetFocusedElement(); if (focusedElement == null) { this.focusedTypeRun.Text = "null"; this.focusedNameRun.Text = String.Empty; this.focusedContentRun.Text = String.Empty; } else { this.focusedTypeRun.Text = focusedElement.GetType().Name; this.focusedNameRun.Text = GetName(focusedElement); this.focusedContentRun.Text = GetContent(focusedElement); } // Update the outline around the focused element. UIElement element = focusedElement as UIElement; if (element != null) { Rect bounds = new Rect(new Point(0, 0), element.RenderSize); bounds = element.TransformToVisual(Window.Current.Content).TransformBounds(bounds); double left = Math.Max(bounds.Left - highlightThickness, 0); double top = Math.Max(bounds.Top - highlightThickness, 0); double right = Math.Min(bounds.Right + highlightThickness, Window.Current.Bounds.Width); double bottom = Math.Min(bounds.Bottom + highlightThickness, Window.Current.Bounds.Height); Canvas.SetLeft(this.highlightRectangle, left); Canvas.SetTop(this.highlightRectangle, top); this.highlightRectangle.Width = Math.Max(0, right - left); this.highlightRectangle.Height = Math.Max(0, bottom - top); } // Close and re-open the popup to make sure it appears in front of all other popups. this.popup.IsOpen = false; this.popup.IsOpen = true; }
/// <summary> /// Method to handle the preview key down. /// </summary> /// <param name="e">KeyEvent arguments.</param> protected override void OnPreviewKeyDown(KeyEventArgs e) { base.OnPreviewKeyDown(e); var fs = FocusManager.GetFocusScope(this); var o = FocusManager.GetFocusedElement(fs); if (e.Key == Key.Escape) { PopupControl.IsOpen = false; Focus(); e.Handled = true; } else if (e.Key == Key.Down) { if (listBox != null && o == this) { raiseTextChanged = true; listBox.Focus(); raiseTextChanged = false; } } }
void ExecuteCommand(ICommand command, object caller) { ServiceSingleton.GetRequiredService <IAnalyticsMonitor>() .TrackFeature(command.GetType().FullName, "Menu"); var routedCommand = command as RoutedCommand; if (routedCommand != null) { var target = FocusManager.GetFocusedElement(this); if (routedCommand.CanExecute(caller, target)) { routedCommand.Execute(caller, target); } } else { if (command.CanExecute(caller)) { command.Execute(caller); } } }
public NavigationRootPage() { this.InitializeComponent(); _navHelper = new RootFrameNavigationHelper(rootFrame, NavigationViewControl); SetDeviceFamily(); AddNavigationMenuItems(); Current = this; RootFrame = rootFrame; this.GotFocus += (object sender, RoutedEventArgs e) => { // helpful for debugging focus problems w/ keyboard & gamepad if (FocusManager.GetFocusedElement() is FrameworkElement focus) { Debug.WriteLine("got focus: " + focus.Name + " (" + focus.GetType().ToString() + ")"); } }; this.Loaded += (s, e) => { // This is to work around a bug in the NavigationView header that hard-codes the header content to a 48 pixel height. var headerContentControl = NavigationViewControl.GetDescendantsOfType <ContentControl>().Where(c => c.Name == "HeaderContent").FirstOrDefault(); if (headerContentControl != null) { headerContentControl.Height = double.NaN; } }; Gamepad.GamepadAdded += OnGamepadAdded; Gamepad.GamepadRemoved += OnGamepadRemoved; Window.Current.CoreWindow.SizeChanged += (s, e) => UpdateAppTitle(); CoreApplication.GetCurrentView().TitleBar.LayoutMetricsChanged += (s, e) => UpdateAppTitle(); _isKeyboardConnected = Convert.ToBoolean(new KeyboardCapabilities().KeyboardPresent); }
protected override void Page_CharacterReceived(CoreWindow sender, CharacterReceivedEventArgs args) { if (ParentShellPageInstance != null) { if (ParentShellPageInstance.CurrentPageType == typeof(GridViewBrowser) && !IsRenamingItem) { // Don't block the various uses of enter key (key 13) var focusedElement = FocusManager.GetFocusedElement() as FrameworkElement; if (args.KeyCode == 13 || focusedElement is Button || focusedElement is TextBox || focusedElement is PasswordBox || DependencyObjectHelpers.FindParent <ContentDialog>(focusedElement) != null) { return; } base.Page_CharacterReceived(sender, args); FileList.Focus(FocusState.Keyboard); } } }
public void CanChangeFocusAfterUniqueIdReset() { var data = new WinRTCollection(Enumerable.Range(0, 2).Select(i => string.Format("Item #{0}", i))); object dataSource = null; RunOnUIThread.Execute(() => dataSource = MockItemsSource.CreateDataSource(data, supportsUniqueIds: true)); ItemsRepeater repeater = SetupRepeater(dataSource); Control focusedElement = null; RunOnUIThread.Execute(() => { focusedElement = (Control)repeater.TryGetElement(0); focusedElement.Focus(FocusState.Keyboard); }); IdleSynchronizer.Wait(); RunOnUIThread.Execute(() => { data.Reset(); }); IdleSynchronizer.Wait(); RunOnUIThread.Execute(() => { // Still focused. Verify.AreEqual(focusedElement, FocusManager.GetFocusedElement()); // Change focused element. focusedElement = (Control)repeater.TryGetElement(1); focusedElement.Focus(FocusState.Keyboard); }); IdleSynchronizer.Wait(); RunOnUIThread.Execute(() => { // Focus is on the new element. Verify.AreEqual(focusedElement, FocusManager.GetFocusedElement()); }); }
private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e) { Console.WriteLine("!!!!!!!"); IInputElement focusedControl = null; IInputElement focusedControlK = FocusManager.GetFocusedElement(this); string str; if (focusedControlK is DependencyObject) { focusedControl = focusedControlK; str = HelpProvider.GetHelpKey((DependencyObject)focusedControl); } else { str = "NoviLokal"; } HelpProvider.ShowHelp(str, this); }
private void focusUp() { var focusedItem = FocusManager.GetFocusedElement(); if (focusedItem == nameBox) { if (listView.Items.Count != 0) { listViewIndex = listView.Items.Count; FocusManager.TryMoveFocus(FocusNavigationDirection.Previous); ElementSoundPlayer.Play(ElementSoundKind.Focus); } else { addButton.Focus(FocusState.Programmatic); ElementSoundPlayer.Play(ElementSoundKind.Focus); } } else if (focusedItem == addButton) { nameBox.Focus(FocusState.Programmatic); ElementSoundPlayer.Play(ElementSoundKind.Focus); } else if (focusedItem == null || focusedItem is ScrollViewer) { nameBox.Focus(FocusState.Programmatic); ElementSoundPlayer.Play(ElementSoundKind.Focus); } else { listViewIndex--; if (listViewIndex < 1) { addButton.Focus(FocusState.Programmatic); ElementSoundPlayer.Play(ElementSoundKind.Focus); listViewIndex = 1; } } }
private void VisiblePath_LostFocus(object sender, RoutedEventArgs e) { if (FocusManager.GetFocusedElement() is FlyoutBase || FocusManager.GetFocusedElement() is AppBarButton || FocusManager.GetFocusedElement() is Popup) { return; } var element = FocusManager.GetFocusedElement(); var elementAsControl = element as Control; if (elementAsControl.FocusState != FocusState.Programmatic && elementAsControl.FocusState != FocusState.Keyboard) { App.CurrentInstance.NavigationToolbar.IsEditModeEnabled = false; } else { if (App.CurrentInstance.NavigationToolbar.IsEditModeEnabled) { this.VisiblePath.Focus(FocusState.Programmatic); } } }
private void Launcher_KeyUp(object sender, KeyEventArgs e) { if (Keyboard.IsKeyUp(Key.LeftShift) || Keyboard.IsKeyUp(Key.RightShift)) { IsShiftDown = false; } IInputElement focused = FocusManager.GetFocusedElement(this); if (focused is TextBox) { TextBox target = focused as TextBox; if (target.Name == "ConsoleCommandTextBox") { object context = target.DataContext; Executable executable = (context is Executable) ? context as Executable : null; if (executable is null || !executable.AllowCommands) { return; } if (e.Key == Key.Enter) { executable.Write(); } if (e.Key == Key.Up) { executable.PreviousHistoryCommand(); target.CaretIndex = target.Text.Length; } if (e.Key == Key.Down) { executable.NextHistoryCommand(); target.CaretIndex = target.Text.Length; } } } }
/// <summary> /// F1 リボン マスタ参照 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public override void OnF1Key(object sender, KeyEventArgs e) { try { object elmnt = FocusManager.GetFocusedElement(this); var tokBox = ViewBaseCommon.FindVisualParent <M01_TOK_TextBox>(elmnt as Control); if (tokBox != null) { // 取引先テキストの場合 tokBox.OpenSearchWindow(this); } else if (isFocusedSupCode) { // 取引先の場合、別テキストに枝番設定の為独自処理 SCHM01_TOK di = new SCHM01_TOK(); di.TwinTextBox = new Framework.Windows.Controls.UcLabelTwinTextBox(); if (di.ShowDialog(this) == true) { this.TORI_CODE.Text = di.TwinTextBox.Text1; this.TORI_EDA.Text = di.TwinTextBox.Text2; SearchSupplierData(int.Parse(取引先コード), int.Parse(枝番)); } } else { // 取引先以外はFW標準で開く ViewBaseCommon.CallMasterSearch(this, this.MasterMaintenanceWindowList); } } catch (Exception ex) { appLog.Error("検索画面起動エラー", ex); ErrorMessage = "システムエラーです。サポートへご連絡ください。"; } }
/// <summary> /// F2 リボン マスタ入力 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public override void OnF2Key(object sender, KeyEventArgs e) { try { object elmnt = FocusManager.GetFocusedElement(this); var spgrid = ViewBaseCommon.FindVisualParent <GcSpreadGrid>(elmnt as Control); if (spgrid == null) { ViewBaseCommon.CallMasterMainte(this.MasterMaintenanceWindowList); } else { #region スプレッド内のイベント処理 if (gridCtl.ActiveColumnIndex == GridColumnsMapping.自社品番.GetHashCode()) { // 品番マスタ表示 MST02010 M09Form = new MST02010(); M09Form.Show(this); } else if (gridCtl.ActiveColumnIndex == GridColumnsMapping.摘要.GetHashCode()) { // 摘要マスタ表示 MST08010 M11Form = new MST08010(); M11Form.Show(this); } #endregion } } catch (Exception ex) { appLog.Error("メンテ画面起動エラー", ex); ErrorMessage = "システムエラーです。サポートへご連絡ください。"; } }
/// <summary> /// Begins the edit. /// </summary> private void BeginEdit() { if (this.textBox != null) { throw new InvalidOperationException(); } var scope = FocusManager.GetFocusScope(this); this.oldfocus = FocusManager.GetFocusedElement(scope); this.textBox = new TextBox(); this.textBox.SetBinding( TextBox.TextProperty, new Binding("Text") { Source = this, UpdateSourceTrigger = UpdateSourceTrigger.Explicit }); Grid.SetColumn(this.textBox, Grid.GetColumn(this)); Grid.SetColumnSpan(this.textBox, Grid.GetColumnSpan(this)); this.Visibility = Visibility.Collapsed; var p = this.Parent as Panel; if (p != null) { int index = p.Children.IndexOf(this); p.Children.Insert(index, this.textBox); } this.textBox.HorizontalAlignment = this.HorizontalAlignment; this.textBox.VerticalAlignment = this.VerticalAlignment; this.textBox.HorizontalContentAlignment = this.HorizontalContentAlignment; this.textBox.VerticalContentAlignment = this.VerticalContentAlignment; this.textBox.LostFocus += this.TextBoxLostFocus; this.textBox.KeyDown += this.TextBoxKeyDown; this.textBox.CaretIndex = this.textBox.Text.Length; this.textBox.SelectAll(); this.textBox.Focus(); }
/// <summary> /// Visual Studio 2012 introduced a new form of incremental search in the find / replace UI /// implementation. It doesn't implement the IIncrementalSearch interface and doesn't expose /// whether or not it's active via any public API. /// /// The best way to find if it's active is to look for the adornment itself and see if it or /// it's descendant has focus. Because Visual Studio is using WPF hosted in a HWND it doesn't /// actually have keyboard focus, just normal focus /// </summary> internal bool IsIncrementalSearchActive2012(ITextView textView) { var wpfTextView = textView as IWpfTextView; if (wpfTextView == null) { return(false); } var adornmentLayer = wpfTextView.GetAdornmentLayerNoThrow("FindUIAdornmentLayer", s_findUIAdornmentLayerKey); if (adornmentLayer == null) { return(false); } foreach (var element in adornmentLayer.Elements) { var adornment = element.Adornment; if (adornment.Visibility == Visibility.Visible && adornment.GetType().Name == "FindUI") { var scope = FocusManager.GetFocusScope(adornment); if (scope == null) { continue; } var focusedElement = FocusManager.GetFocusedElement(scope) as UIElement; if (focusedElement != null && focusedElement != wpfTextView.VisualElement && focusedElement.IsDescendantOf(adornment)) { return(true); } } } return(false); }
/// <summary> /// F1 リボン マスタ検索 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public override void OnF1Key(object sender, KeyEventArgs e) { try { var ctl = FocusManager.GetFocusedElement(this); var uTwin = ViewBaseCommon.FindVisualParent <UcLabelTwinTextBox>(ctl as UIElement); if (uTwin == null) { ViewBaseCommon.CallMasterSearch(this, this.MasterMaintenanceWindowList); } else { // 商品コード指定 if (uTwin.DataAccessName == "M09_MYHIN") { // 雑コード非表示 int[] disableItem = new [] { 3 }; SCHM09_MYHIN myhin = new SCHM09_MYHIN(disableItem); myhin.TwinTextBox = uTwin; if (myhin.ShowDialog(this) == true) { this.Product.Text1 = myhin.SelectedRowData["自社品番"].ToString(); this.Product.Text2 = myhin.SelectedRowData["自社品名"].ToString(); } } else { ViewBaseCommon.CallMasterSearch(this, this.MasterMaintenanceWindowList); } } } catch (Exception ex) { appLog.Error("検索画面起動エラー", ex); ErrorMessage = "システムエラーです。サポートへご連絡ください。"; } }
void SerialDataReceived(object sender, SerialDataReceivedEventArgs e, byte[] bits) { bool bIsTxtBox = false; Dispatcher.Invoke(() => { var con = FocusManager.GetFocusedElement(gdInput); if (con is TextBox tb) { bIsTxtBox = true; } }); if (bIsTxtBox) { _serialRecvBuf += Encoding.Default.GetString(bits).ToUpper(); if (_serialRecvBuf.Contains("\n")) { string strTxt = _serialRecvBuf.Split('\n')[0]; _serialRecvBuf = _serialRecvBuf.Split('\n')[1]; string[] codes = strTxt.Trim().Split('*'); if (codes != null) { if (codes.Length > 2) { _obdTest.StrVIN_IN = codes[2]; } _obdTest.StrType_IN = codes[0]; Dispatcher.Invoke(() => { txtBoxVIN.Text = _obdTest.StrVIN_IN; txtBoxVehicleType.Text = _obdTest.StrType_IN; }); } if (_obdTest.StrVIN_IN.Length == 17 && _obdTest.StrType_IN.Length >= 10) { Task.Factory.StartNew(StartOBDTest); } } } }
void FlushEdits() { UIElement oldFocus = null; //check if property grid has keyboard focus within, if yes - get focused control if (null != this.propertyInspector && this.propertyInspector.IsKeyboardFocusWithin) { oldFocus = FocusManager.GetFocusedElement(this.propertyInspector) as UIElement; } //check if view has keyboard focus within, if yes - get focused control if (null != this.view && this.view.IsKeyboardFocusWithin) { oldFocus = FocusManager.GetFocusedElement(this.view) as UIElement; } if (null != oldFocus) { RoutedCommand cmd = DesignerView.CommitCommand as RoutedCommand; if (cmd != null) { cmd.Execute(null, oldFocus); } } //commit changes within arguments and variables editor var designerView = this.Context.Services.GetService <DesignerView>(); if (null != designerView) { if (null != designerView.arguments1) { DataGridHelper.CommitPendingEdits(designerView.arguments1.argumentsDataGrid); } if (null != designerView.variables1) { DataGridHelper.CommitPendingEdits(designerView.variables1.variableDataGrid); } } }
public NavigationRootPage() { this.InitializeComponent(); _navHelper = new RootFrameNavigationHelper(rootFrame, NavigationViewControl); SetDeviceFamily(); AddNavigationMenuItems(); Current = this; RootFrame = rootFrame; this.GotFocus += (object sender, RoutedEventArgs e) => { // helpful for debugging focus problems w/ keyboard & gamepad if (FocusManager.GetFocusedElement() is FrameworkElement focus) { Debug.WriteLine("got focus: " + focus.Name + " (" + focus.GetType().ToString() + ")"); } }; Gamepad.GamepadAdded += OnGamepadAdded; Gamepad.GamepadRemoved += OnGamepadRemoved; Window.Current.SetTitleBar(AppTitleBar); CoreApplication.GetCurrentView().TitleBar.LayoutMetricsChanged += (s, e) => UpdateAppTitle(s); _isKeyboardConnected = Convert.ToBoolean(new KeyboardCapabilities().KeyboardPresent); // remove the solid-colored backgrounds behind the caption controls and system back button // This is done when the app is loaded since before that the actual theme that is used is not "determined" yet Loaded += delegate(object sender, RoutedEventArgs e) { ApplicationViewTitleBar titleBar = ApplicationView.GetForCurrentView().TitleBar; titleBar.ButtonBackgroundColor = Colors.Transparent; titleBar.ButtonInactiveBackgroundColor = Colors.Transparent; }; }
private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e) { IInputElement focusedControl; if (Application.Current.Windows[1] is UnosManifestacija) { focusedControl = FocusManager.GetFocusedElement(Application.Current.Windows[2]); } else { focusedControl = FocusManager.GetFocusedElement(Application.Current.Windows[1]); } if (focusedControl is DependencyObject) { string str = HelpProvider.GetHelpKey((DependencyObject)focusedControl); HelpProvider.ShowHelp(str, this); } else { HelpProvider.ShowHelp("unosEtikete.html", this); } }
private void VariableListKeyPress(object sender, KeyEventArgs e) { var listView = sender as ListView; if (listView != null && listView.SelectedItem != null && e.Key == Key.Delete) { var focusedElement = FocusManager.GetFocusedElement(this); if (!(focusedElement is ListViewItem)) { return; } var item = listView.SelectedItem as ResultFieldModel; if (item == null || item.IsDefault) { return; } var viewModel = DataContext as ResultTypeViewModel; viewModel.ResultFields.Remove(item); } }
/// <summary> /// Handles key down keyboard control for the context menu. /// </summary> protected override void OnKeyDown(KeyRoutedEventArgs e) { if (_isContextFlyoutAPIPresent == false) { // Handle Shift+F10 and the Menu key. if (e.Key == Windows.System.VirtualKey.Shift) { _isShiftPressed = true; } // Shift+F10 // The 'Menu' key next to Right Ctrl on most keyboards else if ((_isShiftPressed && e.Key == Windows.System.VirtualKey.F10) || e.Key == Windows.System.VirtualKey.Application) { var focusedElement = FocusManager.GetFocusedElement() as UIElement; ShowContextMenu(focusedElement, new Point(0, 0)); e.Handled = true; } } base.OnKeyDown(e); }
private void OnKeyDown(object sender, KeyRoutedEventArgs e) { // Handle Shift+F10 // Handle MenuKey if (e.Key == VirtualKey.Shift) { this._isShiftPressed = true; } // Shift+F10 else if (this._isShiftPressed && e.Key == VirtualKey.F10) { this.ShowMenu(FocusManager.GetFocusedElement() as UIElement, new Point(0, 0)); e.Handled = true; } // The 'Menu' key next to Right Ctrl on most keyboards else if (e.Key == VirtualKey.Application) { this.ShowMenu(FocusManager.GetFocusedElement() as UIElement, new Point(0, 0)); e.Handled = true; } }
private void TextBoxAutoComplete_LostFocus(object sender, RoutedEventArgs e) { var focused_element = FocusManager.GetFocusedElement(Application.Current.Windows.OfType <Window>().SingleOrDefault(x => x.IsActive)); if (focused_element != null) { var elementType = focused_element.GetType(); var elementName = ((FrameworkElement)focused_element).Name; if (elementType != null && elementName != null) { if (elementType == typeof(ComboBoxItem) || elementName.Equals("ComboAutoComplete")) { ComboAutoComplete.IsDropDownOpen = true; } else { ComboAutoComplete.IsDropDownOpen = false; } } } }