Text Selection
As you already know, you can select text in any text box by clicking and dragging with the mouse or holding down Shift while you move through the text with the arrow keys. The TextBox class also gives you the ability to determine or change the currently selected text pro-grammatically, using the SelectionStart, SelectionLength, and SelectedText properties.
SelectionStart identifies the zero-based position where the selection begins. For example, if you set this property to 10, the first selected character is the 11th character in the text box. The Selection Length indicates the total number of selected characters. (A value of 0 indicates no selected characters.) Finally, the SelectedText property allows you to quickly examine or change the selected text in the text box.
You can react to the selection being changed by handling the SelectionChanged event. Here's an example that reacts to this event and displays the current selection information:
private void txt_SelectionChanged(object sender, RoutedEventArgs e) {
if (txtSelection == null) return;
txtSelection.Text = String.Format(
"Selection from {0} to {1} is \"{2}\"", txt.SelectionStart, txt.SelectionLength, txt.SelectedText);
Figure 5-13 shows the result.
|
g Çiluprliijht Pmjm+Tpit Parjp - WinHnim Tr.tprn»! Fv 1 1= @ |—fct- 1 | ||||
|
1 S D:\Code\Pro Silverlight\Chapter05\Elemei | X, j | ||||
|
<k « |
S Silverlight Project Test P... |
A *#.T | ||
|
Select a |
^p test the SelectionChanged event. | |||
|
Selection from 9 to 6 is "word t" | ||||
|
Internet | Protected Mode: On |
+¿100% Ä | |||
Figure 5-13. Selecting text
Post a comment