void AssociatedObject_LostFocus(object sender, RoutedEventArgs e) { // _no exist if (_Child == null) { this.IsOpen = false; return; } // Where is focus var m_wind = GetAncestorTop <Window>(this.AssociatedObject); IInputElement m_inputElem = FocusManager.GetFocusedElement(m_wind); // If selected mouse or other touch device if (typeof(ListBoxItem) == m_inputElem.GetType()) { var m_testAnces = GetAncestorTop <ListBox>(m_inputElem as ListBoxItem); if (_Child.Equals(m_testAnces)) { return; } } ; // is exist if (!_Child.Equals(m_inputElem)) { this.IsOpen = false; } }
/// <summary> /// Focuses a control. /// </summary> /// <param name="control">The control to focus.</param> /// <param name="keyboardNavigated"> /// Whether the control was focused by a keypress (e.g. the Tab key). /// </param> public void Focus(IInputElement control, bool keyboardNavigated = false) { if (control != null) { var scope = GetFocusScopeAncestors(control) .FirstOrDefault(); if (scope != null) { this.Scope = scope; this.SetFocusedElement(scope, control, keyboardNavigated); System.Diagnostics.Debug.WriteLine("Focused " + control.GetType().Name); } } else if (this.Current != null) { // If control is null, set focus to the topmost focus scope. foreach (var scope in GetFocusScopeAncestors(this.Current).Reverse().ToList()) { IInputElement element; if (this.focusScopes.TryGetValue(scope, out element)) { this.Focus(element, keyboardNavigated); break; } } } }
/// <summary> /// Double clicking a result item will attempt to open the item's URL /// in whatever program they have associated with URLs. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void dataGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e) { // If the user is clicking the scrollbar (the arrow // or the "thumb"), don't attempt to open an item in the browser IInputElement element = e.MouseDevice.DirectlyOver; if (element != null && element is FrameworkElement) { var elementType = element.GetType(); if (elementType == typeof(System.Windows.Controls.Primitives.RepeatButton) || elementType == typeof(System.Windows.Controls.Primitives.Thumb)) { return; } } if (ResultGrid.SelectedItem == null) { return; } AmazonItem item = ResultGrid.SelectedItem as AmazonItem; if (item.URL == null) { MessageBox.Show("The item's URL cannot be parsed."); return; } OpenWebpage(item.URL.ToString()); }
/// <summary> /// Constructs an instance of the KeyboardFocusChangedEventArgs class. /// </summary> /// <param name="keyboard"> /// The logical keyboard device associated with this event. /// </param> /// <param name="timestamp"> /// The time when the input occured. /// </param> /// <param name="oldFocus"> /// The element that previously had focus. /// </param> /// <param name="newFocus"> /// The element that now has focus. /// </param> public KeyboardFocusChangedEventArgs(KeyboardDevice keyboard, int timestamp, IInputElement oldFocus, IInputElement newFocus) : base(keyboard, timestamp) { if (oldFocus != null && !InputElement.IsValid(oldFocus)) throw new InvalidOperationException(SR.Get(SRID.Invalid_IInputElement, oldFocus.GetType())); if (newFocus != null && !InputElement.IsValid(newFocus)) throw new InvalidOperationException(SR.Get(SRID.Invalid_IInputElement, newFocus.GetType())); _oldFocus = oldFocus; _newFocus = newFocus; }
/// <summary> /// Gets active text box. /// </summary> /// <returns></returns> private TextBox GetActiveTextBox() { IInputElement focusedControl = FocusManager.GetFocusedElement(this); if (focusedControl == null) { return(null); } if (focusedControl.GetType() == typeof(TextBox)) { return((TextBox)focusedControl); } return(null); }
/// <summary> /// If the user clicks in a data grid area that is not a result, remove the /// grid selection. /// </summary> /// This is to prevent the user from being able to double click /// an empty part of the data grid to open a selected item in a browser tab. /// The intended behavior is to only open an item in a browser if the user /// double-clicks directly on a data grid result. /// <param name="sender"></param> /// <param name="e"></param> void dataGrid_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { IInputElement element = e.MouseDevice.DirectlyOver; if (element != null && element is FrameworkElement) { // If the element selected is of type scroll viewer, it means that the // user is not clicking on a data grid result. In that case, remove // the current selection if (element.GetType() == typeof(System.Windows.Controls.ScrollViewer)) { ResultGrid.SelectedIndex = -1; } } }
/// <summary> /// Gets active text box. /// </summary> /// <returns></returns> private TextBox GetActiveTextBox() { IInputElement focusedControl = FocusManager.GetFocusedElement(Application.Current.Windows[0]); if (focusedControl == null) return null; if (focusedControl.GetType() == typeof(TextBox)) { var txt = (TextBox)focusedControl; var tag = txt.Tag as string; if (tag != "SettingsTxt") return txt; } return null; }
// Return true if the current focus is in a textbox or combobox data control private bool SendKeyToDataEntryControlOrMenu(KeyEventArgs eventData) { // check if each menu type is open // it is sufficient to check one always visible item from each top level menu (file, edit, etc.) // NOTE: this must be kept in sync with the menu definitions in XAML if (this.MenuItemExit.IsVisible || this.MenuItemCopyPreviousValues.IsVisible || this.MenuItemViewNextImage.IsVisible || this.MenuItemSelectAllFiles.IsVisible || this.MenuItemAbout.IsVisible) { return(true); } // by default focus will be on the MarkableCanvas // opening a menu doesn't change the focus IInputElement focusedElement = FocusManager.GetFocusedElement(this); if (focusedElement == null) { return(false); } // check if focus is on a control // NOTE: this list must be kept in sync with the System.Windows classes used by the classes in Timelapse\Util\DataEntry*.cs Type type = focusedElement.GetType(); if (Constant.Control.KeyboardInputTypes.Contains(type)) { // send all keys to controls by default except // - escape as that's a natural way to back out of a control (the user can also hit enter) // - tab as that's the Windows keyboard navigation standard for moving between controls this.FilePlayer_Stop(); // In case the FilePlayer is going return(eventData.Key != Key.Escape && eventData.Key != Key.Tab); } return(false); }
/// <summary> /// Focuses the keyboard on a particular element. /// </summary> /// <param name="element"> /// The element to focus the keyboard on. /// </param> public IInputElement Focus(IInputElement element) { DependencyObject oFocus = null; bool forceToNullIfFailed = false; // Validate that if elt is either a UIElement or a ContentElement. if (element != null) { if (!InputElement.IsValid(element)) { #pragma warning suppress 6506 // element is obviously not null throw new InvalidOperationException(SR.Get(SRID.Invalid_IInputElement, element.GetType())); } oFocus = (DependencyObject)element; } // If no element is given for focus, use the root of the active source. if (oFocus == null && _activeSource != null) { oFocus = _activeSource.Value.RootVisual as DependencyObject; forceToNullIfFailed = true; } Focus(oFocus, true, true, forceToNullIfFailed); return((IInputElement)_focus); }
public Point GetPosition(IInputElement relativeTo) { VerifyAccess(); // Validate that relativeTo is either a UIElement or a ContentElement if (relativeTo != null && !InputElement.IsValid(relativeTo)) { throw new InvalidOperationException(SR.Get(SRID.Invalid_IInputElement, relativeTo.GetType())); } PresentationSource relativePresentationSource = null; if (relativeTo != null) { DependencyObject dependencyObject = relativeTo as DependencyObject; DependencyObject containingVisual = InputElement.GetContainingVisual(dependencyObject); if(containingVisual != null) { relativePresentationSource = PresentationSource.CriticalFromVisual(containingVisual); } } else { if (_inputSource != null) { relativePresentationSource = _inputSource.Value; } } // Verify that we have a valid PresentationSource with a valid RootVisual // - if we don't we won't be able to invoke ClientToRoot or TranslatePoint and // we will just return 0,0 if (relativePresentationSource == null || relativePresentationSource.RootVisual == null) { return new Point(0, 0); } Point ptClient = PointUtil.ScreenToClient(_lastScreenLocation, relativePresentationSource); Point ptRoot = PointUtil.ClientToRoot(ptClient, relativePresentationSource); Point ptRelative = InputElement.TranslatePoint(ptRoot, relativePresentationSource.RootVisual, (DependencyObject)relativeTo); return ptRelative; }
public void Execute(object parameter, IInputElement target) { // We only support UIElement, ContentElement and UIElement3D if ((target != null) && !InputElement.IsValid(target)) { throw new InvalidOperationException(SR.Get(SRID.Invalid_IInputElement, target.GetType())); } if (target == null) { target = FilterInputElement(Keyboard.FocusedElement); } ExecuteImpl(parameter, target, false); }
// Move the focus (usually because of tabbing or shift-tab) // It cycles between the data entry controls and the CopyPrevious button private void MoveFocusToNextOrPreviousControlOrCopyPreviousButton(bool moveToPreviousControl) { // identify the currently selected control // if focus is currently set to the canvas this defaults to the first or last control, as appropriate int currentControl = moveToPreviousControl ? this.DataEntryControls.Controls.Count : -1; Type type; IInputElement focusedElement = FocusManager.GetFocusedElement(this); if (focusedElement != null) { type = focusedElement.GetType(); // If we are moving the focus from outside to one of the controls in the data panel or the copy previous button, // then try to restore the focus to the last control that had the focus. if (Constant.Control.KeyboardInputTypes.Contains(type) == false && focusedElement != this.CopyPreviousValuesButton) { if (this.lastControlWithFocus != null && this.lastControlWithFocus.IsEnabled == true) { Keyboard.Focus(this.lastControlWithFocus); this.CopyPreviousValuesSetEnableStatePreviewsAndGlowsAsNeeded(); return; } } // Otherwise, try to find the control that has the current focus if (Constant.Control.KeyboardInputTypes.Contains(type)) { if (DataEntryHandler.TryFindFocusedControl(focusedElement, out DataEntryControl focusedControl)) { int index = 0; foreach (DataEntryControl control in this.DataEntryControls.Controls) { if (Object.ReferenceEquals(focusedControl, control)) { // We found it, so no need to look further currentControl = index; break; } ++index; } } } } // Then move to the next or previous control as available Func <int, int> incrementOrDecrement; if (moveToPreviousControl) { incrementOrDecrement = (int index) => { return(--index); }; } else { incrementOrDecrement = (int index) => { return(++index); }; } for (currentControl = incrementOrDecrement(currentControl); currentControl > -1 && currentControl < this.DataEntryControls.Controls.Count; currentControl = incrementOrDecrement(currentControl)) { DataEntryControl control = this.DataEntryControls.Controls[currentControl]; if (control.ContentReadOnly == false && control.IsContentControlEnabled == true && this.IsControlIncludedInTabOrder(control)) { this.lastControlWithFocus = control.Focus(this); // There is a bug with Avalon: when the data control pane is floating the focus does not go to it via the above call // (although it does when its docked). // Setting the focus to the actual content control seems to fix it. control.GetContentControl.Focus(); return; } } // if we've gone thorugh all the controls and couldn't set the focus, then we must be at the beginning or at the end. if (this.CopyPreviousValuesButton.IsEnabled) { // So set the focus to the Copy PreviousValuesButton, unless it is disabled. this.CopyPreviousValuesButton.Focus(); this.lastControlWithFocus = this.CopyPreviousValuesButton; this.CopyPreviousValuesSetEnableStatePreviewsAndGlowsAsNeeded(); } else { // Skip the CopyPreviousValuesButton, as it is disabled. DataEntryControl candidateControl = moveToPreviousControl ? this.DataEntryControls.Controls.Last() : this.DataEntryControls.Controls.First(); if (moveToPreviousControl) { // Find the LAST control foreach (DataEntryControl control in this.DataEntryControls.Controls) { if (control.ContentReadOnly == false) { candidateControl = control; } } } else { // Find the FIRST control foreach (DataEntryControl control in this.DataEntryControls.Controls) { if (control.ContentReadOnly == false) { candidateControl = control; break; } } } if (candidateControl != null) { this.lastControlWithFocus = candidateControl.Focus(this); } } }
//Обработка действий при нажатии на ЛКМ в рабочей области private void WorkSpace_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { thickness = Convert.ToDouble(FigureThickness.Text); mousePosition = Mouse.GetPosition(WorkSpace); Color color = ColorPickerButton.SelectedColor.Value; SolidColorBrush myBrush = new(color); IInputElement inputElement = Mouse.DirectlyOver;//Поиск объектов под мышью if (CreateLineButton.IsChecked == false) { if (inputElement.GetType() != typeof(Canvas)) { currentFigure = (Shape)inputElement; } } if (selectedAction == ButtonType.NoneB) { if (inputElement is Polyline && e.ClickCount == 2) { graphicElements.InsertPointIntoLine((Shape)inputElement, mousePosition); } } else if (selectedAction == ButtonType.rectB) { currentFigure = graphicElements.CreateRectangle(new Rect(mousePosition.X, mousePosition.Y, mousePosition.X, mousePosition.Y), myBrush, Convert.ToInt16(FigureThickness.Text)); } else if (selectedAction == ButtonType.lineB) { if (polylinestate == false) { if (inputElement is Polyline) { graphicElements.InsertPointIntoLine((Shape)inputElement, mousePosition); } else { polylinestate = true; currentFigure = graphicElements.AddLine(mousePosition, myBrush, thickness); } } else { if (currentFigure != null) { if (e.ClickCount == 2) { polylinestate = false; } else { graphicElements.AddPointToLine(currentFigure, mousePosition); } } } } else if (selectedAction == ButtonType.fillB) { if (inputElement is not Canvas) { GraphicElements.Fill(currentFigure, ColorPickerButton.SelectedColor.Value); } } else if (selectedAction == ButtonType.FillBorderB) { if (inputElement is not Canvas) { GraphicElements.FillBorder(currentFigure, ColorPickerButton.SelectedColor.Value, thickness); } } else if (selectedAction == ButtonType.deleteB) { if (inputElement is not Canvas) { graphicElements.DeleteFigure(currentFigure); } } else if (selectedAction == ButtonType.moveB) { ClickCount = e.ClickCount; } else if (selectedAction == ButtonType.scaleB) { if (inputElement is not Canvas) { hitType = BorderCheck(currentFigure, mousePosition); } } previousMouseState = 1; }
/// <summary> /// Captures this device to a particular element. /// </summary> /// <param name="element">The element this device will be captured to.</param> /// <param name="captureMode">The type of capture to use.</param> /// <returns>true if capture was changed, false otherwise.</returns> public bool Capture(IInputElement element, CaptureMode captureMode) { VerifyAccess(); // If the element is null or captureMode is None, ensure // that the other parameter is consistent. if ((element == null) || (captureMode == CaptureMode.None)) { element = null; captureMode = CaptureMode.None; } UIElement uiElement; ContentElement contentElement; UIElement3D uiElement3D; CastInputElement(element, out uiElement, out contentElement, out uiElement3D); if ((element != null) && (uiElement == null) && (contentElement == null) && (uiElement3D == null)) { throw new ArgumentException(SR.Get(SRID.Invalid_IInputElement, element.GetType()), "element"); } if (_captured != element) { // Ensure that the new element is visible and enabled if ((element == null) || (((uiElement != null) && uiElement.IsVisible && uiElement.IsEnabled) || ((contentElement != null) && contentElement.IsEnabled) || ((uiElement3D != null) && uiElement3D.IsVisible && uiElement3D.IsEnabled))) { IInputElement oldCapture = _captured; _captured = element; _captureMode = captureMode; UIElement oldUIElement; ContentElement oldContentElement; UIElement3D oldUIElement3D; CastInputElement(oldCapture, out oldUIElement, out oldContentElement, out oldUIElement3D); if (oldUIElement != null) { oldUIElement.IsEnabledChanged -= OnReevaluateCapture; oldUIElement.IsVisibleChanged -= OnReevaluateCapture; oldUIElement.IsHitTestVisibleChanged -= OnReevaluateCapture; } else if (oldContentElement != null) { oldContentElement.IsEnabledChanged -= OnReevaluateCapture; } else if (oldUIElement3D != null) { oldUIElement3D.IsEnabledChanged -= OnReevaluateCapture; oldUIElement3D.IsVisibleChanged -= OnReevaluateCapture; oldUIElement3D.IsHitTestVisibleChanged -= OnReevaluateCapture; } if (uiElement != null) { uiElement.IsEnabledChanged += OnReevaluateCapture; uiElement.IsVisibleChanged += OnReevaluateCapture; uiElement.IsHitTestVisibleChanged += OnReevaluateCapture; } else if (contentElement != null) { contentElement.IsEnabledChanged += OnReevaluateCapture; } else if (uiElement3D != null) { uiElement3D.IsEnabledChanged += OnReevaluateCapture; uiElement3D.IsVisibleChanged += OnReevaluateCapture; uiElement3D.IsHitTestVisibleChanged += OnReevaluateCapture; } UpdateReverseInheritedProperty(/* capture = */ true, oldCapture, _captured); if (oldCapture != null) { DependencyObject o = oldCapture as DependencyObject; o.SetValue(UIElement.AreAnyTouchesCapturedPropertyKey, BooleanBoxes.Box(AreAnyTouchesCapturedOrDirectlyOver(oldCapture, /* isCapture = */ true))); } if (_captured != null) { DependencyObject o = _captured as DependencyObject; o.SetValue(UIElement.AreAnyTouchesCapturedPropertyKey, BooleanBoxes.TrueBox); } if (oldCapture != null) { RaiseLostCapture(oldCapture); } if (_captured != null) { RaiseGotCapture(_captured); } // Capture successfully moved, notify the subclass. OnCapture(element, captureMode); Synchronize(); return(true); } else { return(false); } } else { return(true); } }
/// <summary> /// Captures this device to a particular element. /// </summary> /// <param name="element">The element this device will be captured to.</param> /// <param name="captureMode">The type of capture to use.</param> /// <returns>true if capture was changed, false otherwise.</returns> public bool Capture(IInputElement element, CaptureMode captureMode) { VerifyAccess(); // If the element is null or captureMode is None, ensure // that the other parameter is consistent. if ((element == null) || (captureMode == CaptureMode.None)) { element = null; captureMode = CaptureMode.None; } UIElement uiElement; ContentElement contentElement; UIElement3D uiElement3D; CastInputElement(element, out uiElement, out contentElement, out uiElement3D); if ((element != null) && (uiElement == null) && (contentElement == null) && (uiElement3D == null)) { throw new ArgumentException(SR.Get(SRID.Invalid_IInputElement, element.GetType()), "element"); } if (_captured != element) { // Ensure that the new element is visible and enabled if ((element == null) || (((uiElement != null) && uiElement.IsVisible && uiElement.IsEnabled) || ((contentElement != null) && contentElement.IsEnabled) || ((uiElement3D != null) && uiElement3D.IsVisible && uiElement3D.IsEnabled))) { IInputElement oldCapture = _captured; _captured = element; _captureMode = captureMode; UIElement oldUIElement; ContentElement oldContentElement; UIElement3D oldUIElement3D; CastInputElement(oldCapture, out oldUIElement, out oldContentElement, out oldUIElement3D); if (oldUIElement != null) { oldUIElement.IsEnabledChanged -= OnReevaluateCapture; oldUIElement.IsVisibleChanged -= OnReevaluateCapture; oldUIElement.IsHitTestVisibleChanged -= OnReevaluateCapture; } else if (oldContentElement != null) { oldContentElement.IsEnabledChanged -= OnReevaluateCapture; } else if (oldUIElement3D != null) { oldUIElement3D.IsEnabledChanged -= OnReevaluateCapture; oldUIElement3D.IsVisibleChanged -= OnReevaluateCapture; oldUIElement3D.IsHitTestVisibleChanged -= OnReevaluateCapture; } if (uiElement != null) { uiElement.IsEnabledChanged += OnReevaluateCapture; uiElement.IsVisibleChanged += OnReevaluateCapture; uiElement.IsHitTestVisibleChanged += OnReevaluateCapture; } else if (contentElement != null) { contentElement.IsEnabledChanged += OnReevaluateCapture; } else if (uiElement3D != null) { uiElement3D.IsEnabledChanged += OnReevaluateCapture; uiElement3D.IsVisibleChanged += OnReevaluateCapture; uiElement3D.IsHitTestVisibleChanged += OnReevaluateCapture; } UpdateReverseInheritedProperty(/* capture = */ true, oldCapture, _captured); if (oldCapture != null) { DependencyObject o = oldCapture as DependencyObject; o.SetValue(UIElement.AreAnyTouchesCapturedPropertyKey, BooleanBoxes.Box(AreAnyTouchesCapturedOrDirectlyOver(oldCapture, /* isCapture = */ true))); } if (_captured != null) { DependencyObject o = _captured as DependencyObject; o.SetValue(UIElement.AreAnyTouchesCapturedPropertyKey, BooleanBoxes.TrueBox); } if (oldCapture != null) { RaiseLostCapture(oldCapture); } if (_captured != null) { RaiseGotCapture(_captured); } // Capture successfully moved, notify the subclass. OnCapture(element, captureMode); Synchronize(); return true; } else { return false; } } else { return true; } }
public void Execute(object parameter, IInputElement target) { // We only support UIElement, ContentElement and UIElement3D if ((target != null) && !InputElement.IsValid(target)) { throw new InvalidOperationException(SR.Get(SRID.Invalid_IInputElement, target.GetType())); } if (target == null) { target = FilterInputElement(Keyboard.FocusedElement); } ExecuteImpl(parameter, target, false); }
internal bool CriticalCanExecute(object parameter, IInputElement target, bool trusted, out bool continueRouting) { // We only support UIElement, ContentElement, and UIElement3D if ((target != null) && !InputElement.IsValid(target)) { throw new InvalidOperationException(SR.Get(SRID.Invalid_IInputElement, target.GetType())); } if (target == null) { target = FilterInputElement(Keyboard.FocusedElement); } return CanExecuteImpl(parameter, target, trusted, out continueRouting); }
public Point GetPosition(IInputElement relativeTo) { // VerifyAccess(); // Validate that relativeTo is either a UIElement or a ContentElement if (relativeTo != null && !InputElement.IsValid(relativeTo)) { throw new InvalidOperationException(SR.Get(SRID.Invalid_IInputElement, relativeTo.GetType())); } PresentationSource relativePresentationSource = null; if (relativeTo != null) { DependencyObject dependencyObject = relativeTo as DependencyObject; DependencyObject containingVisual = InputElement.GetContainingVisual(dependencyObject); if (containingVisual != null) { relativePresentationSource = PresentationSource.CriticalFromVisual(containingVisual); } } else { if (_inputSource != null) { relativePresentationSource = _inputSource.Value; } } // Verify that we have a valid PresentationSource with a valid RootVisual // - if we don't we won't be able to invoke ClientToRoot or TranslatePoint and // we will just return 0,0 if (relativePresentationSource == null || relativePresentationSource.RootVisual == null) { return new Point(0, 0); } Point ptClient; Point ptRoot; bool success; Point ptRelative; ptClient = GetClientPosition(relativePresentationSource); ptRoot = PointUtil.TryClientToRoot(ptClient, relativePresentationSource, false, out success); if (!success) { // ClientToRoot failed, usually because the client area is degenerate. // Just return 0,0 return new Point(0, 0); } ptRelative = InputElement.TranslatePoint(ptRoot, relativePresentationSource.RootVisual, (DependencyObject)relativeTo); return ptRelative; }
public IInputElement Focus(IInputElement element) { DependencyObject oFocus = null; bool forceToNullIfFailed = false; // Validate that if elt is either a UIElement or a ContentElement. if(element != null) { if(!InputElement.IsValid(element)) { #pragma warning suppress 6506 // element is obviously not null throw new InvalidOperationException(SR.Get(SRID.Invalid_IInputElement, element.GetType())); } oFocus = (DependencyObject) element; } // If no element is given for focus, use the root of the active source. if(oFocus == null && _activeSource != null) { oFocus = _activeSource.Value.RootVisual as DependencyObject; forceToNullIfFailed = true; } Focus(oFocus, true, true, forceToNullIfFailed); return (IInputElement) _focus; }
internal static void TranslateInput(IInputElement targetElement, InputEventArgs inputEventArgs) { if ((targetElement == null) || (inputEventArgs == null)) { return; } ICommand command = null; IInputElement target = null; object parameter = null; // Determine UIElement/ContentElement/Neither type DependencyObject targetElementAsDO = targetElement as DependencyObject; bool isUIElement = InputElement.IsUIElement(targetElementAsDO); bool isContentElement = !isUIElement && InputElement.IsContentElement(targetElementAsDO); bool isUIElement3D = !isUIElement && !isContentElement && InputElement.IsUIElement3D(targetElementAsDO); // Step 1: Check local input bindings InputBindingCollection localInputBindings = null; if (isUIElement) { localInputBindings = ((UIElement)targetElement).InputBindingsInternal; } else if (isContentElement) { localInputBindings = ((ContentElement)targetElement).InputBindingsInternal; } else if (isUIElement3D) { localInputBindings = ((UIElement3D)targetElement).InputBindingsInternal; } if (localInputBindings != null) { InputBinding inputBinding = localInputBindings.FindMatch(targetElement, inputEventArgs); if (inputBinding != null) { command = inputBinding.Command; target = inputBinding.CommandTarget; parameter = inputBinding.CommandParameter; } } // Step 2: If no command, check class input bindings if (command == null) { lock (_classInputBindings.SyncRoot) { Type classType = targetElement.GetType(); while (classType != null) { InputBindingCollection classInputBindings = _classInputBindings[classType] as InputBindingCollection; if (classInputBindings != null) { InputBinding inputBinding = classInputBindings.FindMatch(targetElement, inputEventArgs); if (inputBinding != null) { command = inputBinding.Command; target = inputBinding.CommandTarget; parameter = inputBinding.CommandParameter; break; } } classType = classType.BaseType; } } } // Step 3: If no command, check local command bindings if (command == null) { // Check for the instance level ones Next CommandBindingCollection localCommandBindings = null; if (isUIElement) { localCommandBindings = ((UIElement)targetElement).CommandBindingsInternal; } else if (isContentElement) { localCommandBindings = ((ContentElement)targetElement).CommandBindingsInternal; } else if (isUIElement3D) { localCommandBindings = ((UIElement3D)targetElement).CommandBindingsInternal; } if (localCommandBindings != null) { command = localCommandBindings.FindMatch(targetElement, inputEventArgs); } } // Step 4: If no command, look at class command bindings if (command == null) { lock (_classCommandBindings.SyncRoot) { Type classType = targetElement.GetType(); while (classType != null) { CommandBindingCollection classCommandBindings = _classCommandBindings[classType] as CommandBindingCollection; if (classCommandBindings != null) { command = classCommandBindings.FindMatch(targetElement, inputEventArgs); if (command != null) { break; } } classType = classType.BaseType; } } } // Step 5: If found a command, then execute it (unless it is // the special "NotACommand" command, which we simply ignore without // setting Handled=true, so that the input bubbles up to the parent) if (command != null && command != ApplicationCommands.NotACommand) { // We currently do not support declaring the element with focus as the target // element by setting target == null. Instead, we interpret a null target to indicate // the element that we are routing the event through, e.g. the targetElement parameter. if (target == null) { target = targetElement; } bool continueRouting = false; RoutedCommand routedCommand = command as RoutedCommand; if (routedCommand != null) { if (routedCommand.CriticalCanExecute(parameter, target, inputEventArgs.UserInitiated /*trusted*/, out continueRouting)) { // If the command can be executed, we never continue to route the // input event. continueRouting = false; ExecuteCommand(routedCommand, parameter, target, inputEventArgs); } } else { if (command.CanExecute(parameter)) { command.Execute(parameter); } } // If we mapped an input event to a command, we should always // handle the input event - regardless of whether the command // was executed or not. Unless the CanExecute handler told us // to continue the route. inputEventArgs.Handled = !continueRouting; } }
internal bool CriticalCanExecute(object parameter, IInputElement target, bool trusted, out bool continueRouting) { // We only support UIElement, ContentElement, and UIElement3D if ((target != null) && !InputElement.IsValid(target)) { throw new InvalidOperationException(SR.Get(SRID.Invalid_IInputElement, target.GetType())); } if (target == null) { target = FilterInputElement(Keyboard.FocusedElement); } return(CanExecuteImpl(parameter, target, trusted, out continueRouting)); }
/// <summary> /// Scans input and command bindings for matching gestures and executes the appropriate command /// </summary> /// <remarks> /// Scans for command to execute in the following order: /// - input bindings associated with the targetElement instance /// - input bindings associated with the targetElement class /// - command bindings associated with the targetElement instance /// - command bindings associated with the targetElement class /// </remarks> /// <param name="targetElement">UIElement/ContentElement to be scanned for input and command bindings</param> /// <param name="inputEventArgs">InputEventArgs to be matched against for gestures</param> internal static void TranslateInput(IInputElement targetElement, InputEventArgs inputEventArgs) { if ((targetElement == null) || (inputEventArgs == null)) { return; } ICommand command = null; IInputElement target = null; object parameter = null; // Determine UIElement/ContentElement/Neither type DependencyObject targetElementAsDO = targetElement as DependencyObject; bool isUIElement = InputElement.IsUIElement(targetElementAsDO); bool isContentElement = !isUIElement && InputElement.IsContentElement(targetElementAsDO); bool isUIElement3D = !isUIElement && !isContentElement && InputElement.IsUIElement3D(targetElementAsDO); // Step 1: Check local input bindings InputBindingCollection localInputBindings = null; if (isUIElement) { localInputBindings = ((UIElement)targetElement).InputBindingsInternal; } else if (isContentElement) { localInputBindings = ((ContentElement)targetElement).InputBindingsInternal; } else if (isUIElement3D) { localInputBindings = ((UIElement3D)targetElement).InputBindingsInternal; } if (localInputBindings != null) { InputBinding inputBinding = localInputBindings.FindMatch(targetElement, inputEventArgs); if (inputBinding != null) { command = inputBinding.Command; target = inputBinding.CommandTarget; parameter = inputBinding.CommandParameter; } } // Step 2: If no command, check class input bindings if (command == null) { lock (_classInputBindings.SyncRoot) { Type classType = targetElement.GetType(); while (classType != null) { InputBindingCollection classInputBindings = _classInputBindings[classType] as InputBindingCollection; if (classInputBindings != null) { InputBinding inputBinding = classInputBindings.FindMatch(targetElement, inputEventArgs); if (inputBinding != null) { command = inputBinding.Command; target = inputBinding.CommandTarget; parameter = inputBinding.CommandParameter; break; } } classType = classType.BaseType; } } } // Step 3: If no command, check local command bindings if (command == null) { // Check for the instance level ones Next CommandBindingCollection localCommandBindings = null; if (isUIElement) { localCommandBindings = ((UIElement)targetElement).CommandBindingsInternal; } else if (isContentElement) { localCommandBindings = ((ContentElement)targetElement).CommandBindingsInternal; } else if (isUIElement3D) { localCommandBindings = ((UIElement3D)targetElement).CommandBindingsInternal; } if (localCommandBindings != null) { command = localCommandBindings.FindMatch(targetElement, inputEventArgs); } } // Step 4: If no command, look at class command bindings if (command == null) { lock (_classCommandBindings.SyncRoot) { Type classType = targetElement.GetType(); while (classType != null) { CommandBindingCollection classCommandBindings = _classCommandBindings[classType] as CommandBindingCollection; if (classCommandBindings != null) { command = classCommandBindings.FindMatch(targetElement, inputEventArgs); if (command != null) { break; } } classType = classType.BaseType; } } } // Step 5: If found a command, then execute it (unless it is // the special "NotACommand" command, which we simply ignore without // setting Handled=true, so that the input bubbles up to the parent) if (command != null && command != ApplicationCommands.NotACommand) { // We currently do not support declaring the element with focus as the target // element by setting target == null. Instead, we interpret a null target to indicate // the element that we are routing the event through, e.g. the targetElement parameter. if (target == null) { target = targetElement; } bool continueRouting = false; RoutedCommand routedCommand = command as RoutedCommand; if (routedCommand != null) { if (routedCommand.CriticalCanExecute(parameter, target, inputEventArgs.UserInitiated /*trusted*/, out continueRouting)) { // If the command can be executed, we never continue to route the // input event. continueRouting = false; ExecuteCommand(routedCommand, parameter, target, inputEventArgs); } } else { if (command.CanExecute(parameter)) { command.Execute(parameter); } } // If we mapped an input event to a command, we should always // handle the input event - regardless of whether the command // was executed or not. Unless the CanExecute handler told us // to continue the route. inputEventArgs.Handled = !continueRouting; } }
public void TrackKeyboardFocus() { EventManager.RegisterClassHandler(typeof(UIElement), Keyboard.GotKeyboardFocusEvent, new KeyboardFocusChangedEventHandler((sender, args) => { if (_currentFocused == args.NewFocus) return; _currentFocused = args.NewFocus; if (_currentFocused is FrameworkElement) { new FocusAdorner(_currentFocused as FrameworkElement); } Write((_currentFocused is FrameworkElement ? (_currentFocused as FrameworkElement).Name : "") + "<" + _currentFocused.GetType().Name + ">"); }), true); }
/// <summary> /// Constructs an instance of the KeyboardFocusChangedEventArgs class. /// </summary> /// <param name="keyboard"> /// The logical keyboard device associated with this event. /// </param> /// <param name="timestamp"> /// The time when the input occured. /// </param> /// <param name="oldFocus"> /// The element that previously had focus. /// </param> /// <param name="newFocus"> /// The element that now has focus. /// </param> public KeyboardFocusChangedEventArgs(KeyboardDevice keyboard, int timestamp, IInputElement oldFocus, IInputElement newFocus) : base(keyboard, timestamp) { if (oldFocus != null && !InputElement.IsValid(oldFocus)) { throw new InvalidOperationException(SR.Get(SRID.Invalid_IInputElement, oldFocus.GetType())); } if (newFocus != null && !InputElement.IsValid(newFocus)) { throw new InvalidOperationException(SR.Get(SRID.Invalid_IInputElement, newFocus.GetType())); } _oldFocus = oldFocus; _newFocus = newFocus; }