namespace VideoBrowser.Extensions { using System.Windows; /// /// Defines the . /// public static class FocusExtension { #region Fields public static readonly DependencyProperty IsFocusedProperty = DependencyProperty.RegisterAttached(nameof(IsFocusedProperty).Name(), typeof(bool), typeof(FocusExtension), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnIsFocusedChanged)); public static readonly DependencyProperty TrackFocusProperty = DependencyProperty.RegisterAttached(nameof(TrackFocusProperty).Name(), typeof(bool), typeof(FocusExtension), new PropertyMetadata(false, OnTrackFocusChanged)); #endregion Fields #region Methods /// /// The GetIsFocused. /// /// The obj. /// The . public static bool GetIsFocused(DependencyObject obj) => (bool)obj.GetValue(IsFocusedProperty); /// /// The GetTrackFocus. /// /// The obj. /// The . public static bool GetTrackFocus(DependencyObject obj) { return (bool)obj.GetValue(TrackFocusProperty); } /// /// The SetIsFocused. /// /// The obj. /// The value. public static void SetIsFocused(DependencyObject obj, bool value) => obj.SetValue(IsFocusedProperty, value); /// /// The SetTrackFocus. /// /// The obj. /// The value. public static void SetTrackFocus(DependencyObject obj, bool value) { obj.SetValue(TrackFocusProperty, value); } /// /// The OnGotFocus. /// /// The sender. /// The e. private static void OnGotFocus(object sender, RoutedEventArgs e) { if (!(sender is FrameworkElement element)) { return; } if (!GetIsFocused(element)) { SetIsFocused(element, true); } } /// /// The OnIsFocusedChanged. /// /// The d. /// The e. private static void OnIsFocusedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var element = (FrameworkElement)d; var isFocused = (bool)e.NewValue; if (isFocused) { element.Focus(); } } /// /// The OnLostFocus. /// /// The sender. /// The e. private static void OnLostFocus(object sender, RoutedEventArgs e) { if (!(sender is FrameworkElement element)) { return; } if (GetIsFocused(element)) { SetIsFocused(element, false); } } /// /// The OnTrackFocusChanged. /// /// The d. /// The e. private static void OnTrackFocusChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (!(d is FrameworkElement element)) { return; } var oldValue = (bool)e.OldValue; var newValue = (bool)e.NewValue; if (!oldValue && newValue) // If changed from false to true { element.GotFocus += OnGotFocus; element.LostFocus += OnLostFocus; } else if (oldValue && !newValue) // If changed from true to false { element.GotFocus -= OnGotFocus; element.LostFocus -= OnLostFocus; } } #endregion Methods } }