Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Windows;
- using System.Windows.Controls;
- namespace UI.Extensions
- {
- /// <summary>
- /// Extension to focus UI controls via ViewModels.
- /// xaml: <TextBox Text="Set Text Before FocusExtension to SelectAll" ext:FocusExtension.IsFocused="True" />
- /// Remember to add 'xmlns:ext="clr-namespace:UI.Extensions"' to xaml namespaces
- /// </summary>
- public static class FocusExtension
- {
- public static bool? GetIsFocused(DependencyObject obj)
- {
- return (bool?)obj.GetValue(IsFocusedProperty);
- }
- public static void SetIsFocused(DependencyObject obj, bool? value)
- {
- obj.SetValue(IsFocusedProperty, value);
- }
- public static readonly DependencyProperty IsFocusedProperty =
- DependencyProperty.RegisterAttached(
- "IsFocused", typeof(bool?), typeof(FocusExtension),
- new UIPropertyMetadata(false, OnIsFocusedPropertyChanged));
- private static void OnIsFocusedPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
- {
- var uie = d as UIElement;
- if (uie == null)
- return;
- if (e.NewValue == null)
- return;
- if ((bool)e.NewValue)
- {
- uie.Focus(); // Don't care about false values.
- TextBox tb = uie as TextBox;
- if (tb != null)
- {
- if (!string.IsNullOrEmpty(tb.Text))
- tb.SelectAll();
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement