Thursday, February 26, 2009

Text selection in WPF TextBox

There are so many methods and properties which deals with selection in WPF TextBox.
Name Description
TextBox.Select() Accepts initial position and length of selection.
TextBox.SelectAll() Selects full text.
TextBox.SelectionStart Direct property which tells the start of selection.
TextBox.SelectionLength Direct property which tells the length of selection.
TextBox.SelectedText Gives the currently selected text.

But if you just use these methods and properties the selection will not come as the text won't get selected even if we set these properties or call methods.

The reason for this is very simple.The TextBox is not in focus.So make sure that the TextBox is in focus before using programmatic selection related members.Or give Focus to the TextBox before selecting.


tbResult.SelectionStart = tbResult.Text.IndexOf("ControlTemplate TargetType=");
tbResult.SelectionLength = 230;


  1. Thank you. I was having a problem setting a selection and this post solved it for me.

  2. Thanks for the useful tip! :)