private static void AttachToLoadedEvent(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args) { if (!(dependencyObject is TextBox textBox)) { return; } var enabled = args.NewValue != null && (bool)args.NewValue; if (enabled) { if (textBox.IsLoaded) { // Directly set the focus. TextBoxHelper.SetFocus(textBox, new RoutedEventArgs()); } else { // Apply a handler to the loaded event. TextBoxHelper.AddHandlers(textBox); } } else { TextBoxHelper.RemoveHandlers(textBox); } }
private static void SetFocus(object sender, RoutedEventArgs args) { // Remove this handler. TextBoxHelper.RemoveHandlers(sender); // Cast the framework element to an input element. if (!(sender is IInputElement inputElement)) { return; } // Set the focus. Application.Current.Dispatcher.BeginInvoke ( (Action) delegate { System.Windows.Input.Keyboard.Focus(inputElement); }, System.Windows.Threading.DispatcherPriority.Render ); }
private static void RemoveHandlers(object sender) => TextBoxHelper.RemoveHandlers(sender, null);