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:
           TextBox.PreviewMouseLeftButtonDownEvent, New MouseButtonEventHandler(
                AddressOf SelectivelyIgnoreMouseButton))

           TextBox.MouseDoubleClickEvent, New RoutedEventArgs(
                AddressOf SelectAllText))

           TextBox.GotKeyboardFocusEvent, New RoutedEventArgs(
                AddressOf SelectAllText))

  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.
      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
  End If
End Sub
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: Logo

You are commenting using your 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