Describing the Text Information of TextBox Control in WPF

Introduction

This article explains how to work with the Control's selected text. Here we are using a TexBox Control that is also a complex control with many imporatnt methods, properties and events. We described the information about the text contained in the TextBox control.

Background

I have taken two Labels, a TextBox,  three Buttons and a Checkbox.

1. Here, the SelectedText property is used for Text Selection that returns a string containing the characters that the user has selected in the TextBox.

2. And for obtaining the selection positions  I have used the following properties:

  • CaretIndex
  • SelectionStart
  • SelectionLength

Solution

The SelectedText property is a string containing the characters the user selected in a TextBox. If the user selected all of the available text then the SelectedText and Text properties match.
If no text is selected then the SelectedText property returns an empty string.

Sometimes you won't be interested in just the text that is selected but you will want to know the position of the flashing cursor, or caret, or the highlighted region. This is important if you need to know which characters are selected in a string that is repetitive.

This information is available from the following three properties:

CaretIndex: The CaretIndex property returns or sets the position of the flashing caret. The index is zero-based, so if it returns zero if the cursor is to the left of the first character.
SelectionStart: The SelectionStart property returns the same value as CaretIndex. It is also the position that any selected text starts.
SelectionLength: The SelectionLength property returns the number of characters that are selected. If no selection is present, it returns zero.

Procedure

Step 1

First, create an XAML window containing a window and a grid. In the Grid we have declared grid-row definitions, a Label, a TextBox and a StackPanel in which Button controls are defined. We will name the TextBox "MyTextBox" and pass the value to the SelectionChanged property of the TextBox class. The value passed here is the "MyTextBox_SelctionChanged" event that is generated when we click on the TextBox.

<Window x:Class="TextBoxSelectionDemo.MainWindow"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        Title="TextBox Demo"

        Height="200"

        Width="250">

    <Grid>

        <Grid.RowDefinitions>

            <RowDefinition/>

            <RowDefinition/>

            <RowDefinition/>

            <RowDefinition/>

        </Grid.RowDefinitions>

 

        <Label Content="Enter some text" Margin="5"/>

        <TextBox Grid.Row="1"

                 Name="MyTextBox"

                 Margin="5"

                 SelectionChanged="MyTextBox_SelectionChanged"

                 AutoWordSelection="True" />

.......

........

        

 </Grid>

</Window>

Step 2

Also in the code above, I have created buttons having the propertiies under the StackPanel tag. The values are passed to the Click property of the Button class. Again these values are nothing but the events generated on the click of these buttons. Also, I used a checkbox setting it's Content to auto and it's checked and unchecked property to Auto_checked. And at last I used a label that will show the information of the text in the TextBox.

 <StackPanel Grid.Row="2" Orientation="Horizontal" Margin="2">

            <Button Content="Show" Width="50" Margin="3" Click="ShowButton_Click" />

            <Button Content="Select" Width="50" Margin="3" Click="SelectButton_Click"/>

            <Button Content="All" Width="50" Margin="3" Click="AllButton_Click"/>

            <CheckBox Content="Auto"

                      Margin="3 10"

                      IsChecked="True"

                      Checked="Auto_Checked"

                      Unchecked="Auto_Checked" />

        </StackPanel>

 

        <Label Grid.Row="3" Name="MyLabel" Margin="5"/>

Step 3

Now, we create a class named "MainWindow" in which the events are generated on the click of the buttons.

In the ShowButton_Click event generated on the click of the show button, we will define a method called ShowSelectionInfo() that will show the information of the text in the TextBox.

In the SelectButton_Click event, generated on the click of the select button, we will define a method having parameters, in other words MyTextBox.Select(1,5), that will cut the text after the first letter of text and proceed up to the length of 5 letters from that point (in other words the point after the cutting of the first letter of text).

In the "AllButton_cLick" event, we will provide a "MyTextBox.SelctAll()" method that will show all kinds of information of text present in the TextBox.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Navigation;

using System.Windows.Shapes;

 

namespace TextBoxSelectionDemo

{

    public partial class MainWindow : Window

    {

        public MainWindow()

        {

            InitializeComponent();

        }

 

        private void ShowButton_Click(object sender, RoutedEventArgs e)

        {

            ShowSelectionInfo();

        }

 

        private void SelectButton_Click(object sender, RoutedEventArgs e)

        {

            MyTextBox.Select(1, 5);

        }

 

        private void AllButton_Click(object sender, RoutedEventArgs e)

        {

            MyTextBox.SelectAll();

        }

 

       }

}

Step 4

In the "MyTextBox_SelectionChanged" event, we will pass a method called "ShowSelectionInfo()" that obviously will show all the TextBox text related information. Here we will add the properties to the TextBox. The properties are SelectedText, CaretIndex, SelectionStart and SlectionLength that I described above in the background part.

 private void MyTextBox_SelectionChanged(object sender, RoutedEventArgs e)

        {

            ShowSelectionInfo();

        }

 

        private void ShowSelectionInfo()

        {

            string info = string.Format(

            "'{0}' / Caret {1} / Start {2} / Length {3}",

            MyTextBox.SelectedText,

            MyTextBox.CaretIndex,

            MyTextBox.SelectionStart,

            MyTextBox.SelectionLength);

 

            MyLabel.Content = info;

        }

 

        private void Auto_Checked(object sender, RoutedEventArgs e)

        {

            MyTextBox.AutoWordSelection = ((CheckBox)sender).IsChecked.Value;

        }

 

Output

 
1. On running the application you will get this window.
 
st1 
 
2. When you move the cursor into the TextBox, the label shown below will describe the information related to the TextBox. Since no text is currently available in the TextBox, the label is showing zero values for all the Caret, Start and Length properties.
 
st2 
 
3. When we start to type the text, the values of Caret, Start and Length will start changing and will show the values related to the text. Here the number of letters are ten. 
 
st3 
 
4. Similarly, this one.
 
st4 
 
5. On clicking the "Select" property, the "MyTextBox.select(1,5)" method is called and it will cut the first letter of the text and proceed up to the fifth position after cutting the first letter of the text.
 
st5 
 
6. When we click on the "All" button, all the desired information corresponding to the text will be shown.
 
st6 
 
7. Similarly, this one.
 
st7