#937 – Selecting Text in a TextBox from Code
October 28, 2013 Leave a comment
You can select text in a TextBox from code by using the Select method. This method accepts the following two parameters:
- start – 0-based index for start of selection (int)
- length – number of characters to select (int)
Note that if the TextBox doesn’t currently have focus, the selected text will not be highlighted.
Assume that we have a TextBox, some labels displaying selected text and a Button:
<TextBox Name="txtTest" Margin="5" Height="100" Text="{Binding SomeText}" TextWrapping="Wrap" VerticalScrollBarVisibility="Auto" SelectionChanged="TextBox_SelectionChanged"/> <Label Content="{Binding SelectedText}"/> <StackPanel Orientation="Horizontal"> <Label Content="{Binding SelectionStart}"/> <Label Content="{Binding SelectionLength}"/> </StackPanel> <Button Content="Select Something" Click="Button_Click"/>
The code below then selects some text when the button is pressed.
private void Button_Click(object sender, RoutedEventArgs e) { // Select 10 characters, starting 6th character txtTest.Select(5, 10); // Give focus back to TextBox, so that it // highlights selected text txtTest.Focus(); }