Advertisement
Guest User

FocusManagerExtensions

a guest
Jun 24th, 2010
2,863
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.27 KB | None | 0 0
  1. public class FocusManagerExtensions
  2. {
  3.     public static readonly DependencyProperty IsFocusedProperty = DependencyProperty.RegisterAttached("IsFocused", typeof(bool?), typeof(FocusManagerExtensions), new FrameworkPropertyMetadata(IsFocusedChanged));
  4.     public static bool? GetIsFocused(DependencyObject element)
  5.     {
  6.         if (element == null) {
  7.             throw new ArgumentNullException("element");
  8.         }
  9.  
  10.         return (bool?)element.GetValue(IsFocusedProperty);
  11.     }
  12.  
  13.     public static void SetIsFocused(DependencyObject element, bool? value)
  14.     {
  15.         if (element == null) {
  16.             throw new ArgumentNullException("element");
  17.         }
  18.  
  19.         element.SetValue(IsFocusedProperty, value);
  20.     }
  21.  
  22.     private static void IsFocusedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  23.     {
  24.         object fe = (FrameworkElement)d;
  25.  
  26.         if (e.OldValue == null) {
  27.             fe.GotFocus += FrameworkElement_GotFocus;
  28.             fe.LostFocus += FrameworkElement_LostFocus;
  29.         }
  30.  
  31.         if ((bool)e.NewValue) {
  32.             fe.Focus();
  33.         }
  34.     }
  35.  
  36.     private static void FrameworkElement_GotFocus(object sender, RoutedEventArgs e)
  37.     {
  38.         ((FrameworkElement)sender).SetValue(IsFocusedProperty, true);
  39.     }
  40.  
  41.     private static void FrameworkElement_LostFocus(object sender, RoutedEventArgs e)
  42.     {
  43.         ((FrameworkElement)sender).SetValue(IsFocusedProperty, false);
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement