private static void OnAcceleratorChanged(DependencyObject dpo, DependencyPropertyChangedEventArgs e) { if (Designer.InDesignMode) { return; } Control owner = dpo as Control; if (owner == null) { return; } // Remove any existing accelerator lists for this control, or // dead entries which are not valid anymore. foreach (var entry in ActiveAccelerators .Where(ac => ac.Item2 == owner).ToList()) { ActiveAccelerators.Remove(entry); } if (e.NewValue != null) { string keyText = e.NewValue.ToString(); var watchFor = ParseKeys(keyText); if (watchFor != null && watchFor.Count > 0) { owner.Unloaded += OwnerOnUnloaded; ActiveAccelerators.Add(Tuple.Create(watchFor, owner)); // Set the accelerator/access key for automation if (watchFor.Contains(VirtualKey.Menu) && !watchFor.Contains(VirtualKey.Control)) { AutomationProperties.SetAcceleratorKey(owner, keyText); } else if (watchFor.Contains(VirtualKey.Control) && !watchFor.Contains(VirtualKey.Menu)) { AutomationProperties.SetAccessKey(owner, keyText); } } if (ActiveAccelerators.Count == 1) { Window.Current.Dispatcher.AcceleratorKeyActivated += DispatcherOnAcceleratorKeyActivated; Window.Current.CoreWindow.Activated += CoreWindowOnActivated; } } else { owner.Unloaded -= OwnerOnUnloaded; if (ActiveAccelerators.Count == 0) { Window.Current.Dispatcher.AcceleratorKeyActivated -= DispatcherOnAcceleratorKeyActivated; Window.Current.CoreWindow.Activated -= CoreWindowOnActivated; } } }
/// <summary> /// Provides derived classes an opportunity to handle changes /// to the Shortcut property. /// </summary> /// <param name="oldShortcut">The old Shortcut value</param> /// <param name="newShortcut">The new Shortcut value</param> private void OnShortcutChanged( string oldShortcut, string newShortcut) { AutomationProperties.SetAcceleratorKey(this, newShortcut); if (this.keyGestureRecognizer != null) { this.keyGestureRecognizer.GestureRecognized -= this.OnKeyGestureRecognized; this.keyGestureRecognizer.Dispose(); } this.keyGesture = string.IsNullOrEmpty(newShortcut) ? null : KeyGesture.Parse(newShortcut); if (this.keyGesture != null) { this.keyGestureRecognizer = new KeyGestureRecognizer(this.keyGesture); this.keyGestureRecognizer.GestureRecognized += this.OnKeyGestureRecognized; } this.UpdateToolTip(); }