#936 – TextBox Properties that Reflect Currently Selected Text

The following properties of a TextBox are updated whenever the user changes the currently selected text in a TextBox.

  • SelectedText – the currently selected text (string)
  • SelectionStart – 0-based index into the Text property for the start of the selection  (int)
  • SelectionLength – number of characters selected (int)

The SelectionChanged event will fire whenever the currently selected text changes.

Below, we wire up the SelectionChanged event, capture the values of these properties, and then bind to those values.

        <TextBox 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>
        private void RaisePropertyChanged(string propName)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propName));
        }

        public string SelectedText { get; set; }
        public int SelectionStart { get; set; }
        public int SelectionLength { get; set; }

        private void TextBox_SelectionChanged(object sender, RoutedEventArgs e)
        {
            SelectedText = ((TextBox)sender).SelectedText;
            SelectionStart = ((TextBox)sender).SelectionStart;
            SelectionLength = ((TextBox)sender).SelectionLength;

            RaisePropertyChanged("SelectedText");
            RaisePropertyChanged("SelectionStart");
            RaisePropertyChanged("SelectionLength");
        }

936-001

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: