How to Select Content of TextBox when in Focus

WPF does not support a Select property on the TextBox object. In order to get this functionality I found the following code:

In Application_Startup.vb

  Protected Overrides Sub OnStartup(e as StartupEventArgs)
    ' select the text in a TextBox when it receives focus:
    EventManager.RegisterClassHandler(GetType(TextBox), 
           TextBox.PreviewMouseLeftButtonDownEvent, New MouseButtonEventHandler(
                AddressOf SelectivelyIgnoreMouseButton))

    EventManager.RegisterClassHandler(GetType(TextBox),
           TextBox.MouseDoubleClickEvent, New RoutedEventArgs(
                AddressOf SelectAllText))

    EventManager.RegisterClassHandler(GetType(TextBox),
           TextBox.GotKeyboardFocusEvent, New RoutedEventArgs(
                AddressOf SelectAllText))

    myBase.OnStartUp(e)
  End Sub

The helper methods: selectivelyIgnoreMouseButton(), SelectAllText()

Private Sub SelectivelyIgnoreMouseButton(sender as Object, e As MouseButtonEventArgs)
  ' Find the TextBox
  Dim parent As DependencyObject = TryCast(e.OriginalSource, UIElement)
  While parent IsNot Nothing AndAlso Not (TypeOf parent Is TextBox)
    parent = VisualTreeHelper.GetParent(parent)
  End While
  If parent IsNot Nothing Then
    Dim textbox = DirectCast(parent, TextBox)
    If Not textbox.IsKeyboardFocusWithin Then
      ' If the text box is not yet focussed then give it focus and
      ' stop further processing of this click event.
      textbox.Focus()
      e.Handled = true
  End If

End Sub

private Sub SelectAllText(sender as Object, e as RoutedEventArgs)
  Dim textbox = TryCast(e.OriginalSource, TextBox)
  If textbox IsNot Nothing Then
    textBox.SelectAll()
  End If
End Sub
Advertisements
This entry was posted in WPF and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s