TextBox content selection onFocus().

Aug 10, 2010 at 7:34 AM

I am using MVVM in WPF where I have a View with few text boxes and other controls.
All the controls have tab index set. I want whenever focus comes (using tab or mouse) to any text box, entire content of the text box should get selected (it's a usability requirement).
However my ViewModel does not know about my view so how can I accomplish this without putting code into the codebehind of my view (to maintain separation of concerns--objective of MVVM)?

Anybody, any idea?

Thanks,
vverma01

Aug 12, 2010 at 6:29 PM

Hi All,

I got the solution:

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        EventManager.RegisterClassHandler(typeof(TextBox), UIElement.PreviewMouseLeftButtonDownEvent,
           new MouseButtonEventHandler(SelectivelyHandleMouseButton), true);
        EventManager.RegisterClassHandler(typeof(TextBox), UIElement.GotKeyboardFocusEvent,
          new RoutedEventHandler(SelectAllText), true);

        base.OnStartup(e);
    }

    private static void SelectivelyHandleMouseButton(object sender, MouseButtonEventArgs e)
    {
        var textbox = (sender as TextBox);
        if (textbox != null && !textbox.IsKeyboardFocusWithin)
        {
            if( e.OriginalSource.GetType().Name == "TextBoxView" )
            {
                e.Handled = true;
                textbox.Focus();
            }
        }
    }

    private static void SelectAllText(object sender, RoutedEventArgs e)
    {
        var textBox = e.OriginalSource as TextBox;
        if (textBox != null)
            textBox.SelectAll();
    } 
}

For more details please visit:

http://www.intertech.com/Blog/post/How-to-Select-All-Text-in-a-WPF-Content-on-Focus.aspx

Thanks,

vverma01