Text Selection in a TextBox in Silverlight 3 Application


Introduction

In this article we will see some of the properties related to Text Selection in TextBox Control in Silverlight 3.

Crating Silverlight Project

Fire up Visual Studio 2008 and create a Silverlight Application. Name it as TextSelectionInSL3.

image1.gif

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 programmatically, using the SelectionStart, SelectionLength, and SelectedText properties.

Open the solution in Expression Blend 3 and design your application.

I have designed in the following fashion:

image2.gif

As you see from the above figure, I have a TextBox, and three TextBlocks to display the Selection 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.

Go to Visual Studio and add an event for Selection Changed for the TextBox, follow the code below:

<TextBox x:Name="MyTextBox" Margin="8" Text="TextBox" TextWrapping="Wrap" SelectionChanged="MyTextBox_SelectionChanged"/>

Now add the following code to see how the properties are used.

private void MyTextBox_SelectionChanged(object sender, RoutedEventArgs e)
        {
            TextPosition.Text = String.Format("Selected Position : From {0} To {1}",MyTextBox.SelectionStart, (MyTextBox.SelectionLength+MyTextBox.SelectionStart)-1);
            TextLength.Text = String.Format("Selected Length : {0}", MyTextBox.SelectionLength);
            TextSelected.Text = String.Format("Selected Text : \"{0}\"",MyTextBox.SelectedText);
        }

Now run your application and Type your text and select a particular length. You will see the TextBlocks texts are changing displaying the Selection Position, Selection Length and Selected Text.

image3.gif

Enjoy Coding.

Up Next
    Ebook Download
    View all
    Learn
    View all