This week only. Pastebin PRO Accounts Christmas Special! Don't miss out!Want more features on Pastebin? Sign Up, it's FREE!
Guest

FocusManagerExtensions

By: a guest on Jun 24th, 2010  |  syntax: C#  |  size: 1.27 KB  |  views: 1,290  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
This paste has a previous version, view the difference. Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  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. }
clone this paste RAW Paste Data