Advertisement
andrew4582

WPF Focus Extension

Aug 15th, 2013
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.31 KB | None | 0 0
  1. using System.Windows;
  2. using System.Windows.Controls;
  3.  
  4. namespace UI.Extensions
  5. {
  6.     /// <summary>
  7.     /// Extension to focus UI controls via ViewModels.
  8.     /// xaml: <TextBox Text="Set Text Before FocusExtension to SelectAll" ext:FocusExtension.IsFocused="True" />
  9.     /// Remember to add 'xmlns:ext="clr-namespace:UI.Extensions"' to xaml namespaces
  10.     /// </summary>
  11.     public static class FocusExtension
  12.     {
  13.         public static bool? GetIsFocused(DependencyObject obj)
  14.         {
  15.             return (bool?)obj.GetValue(IsFocusedProperty);
  16.         }
  17.  
  18.         public static void SetIsFocused(DependencyObject obj, bool? value)
  19.         {
  20.             obj.SetValue(IsFocusedProperty, value);
  21.         }
  22.  
  23.         public static readonly DependencyProperty IsFocusedProperty =
  24.                 DependencyProperty.RegisterAttached(
  25.                  "IsFocused", typeof(bool?), typeof(FocusExtension),
  26.                  new UIPropertyMetadata(false, OnIsFocusedPropertyChanged));
  27.  
  28.         private static void OnIsFocusedPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  29.         {
  30.             var uie = d as UIElement;
  31.             if (uie == null)
  32.                 return;
  33.  
  34.             if (e.NewValue == null)
  35.                 return;
  36.  
  37.             if ((bool)e.NewValue)
  38.             {
  39.                 uie.Focus(); // Don't care about false values.
  40.                 TextBox tb = uie as TextBox;
  41.                 if (tb != null)
  42.                 {
  43.                     if (!string.IsNullOrEmpty(tb.Text))
  44.                         tb.SelectAll();
  45.                 }
  46.             }
  47.         }
  48.     }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement