Search code examples
wpfxamltextboxrichtextbox

RichTextBox.SelectionStart could not be found


Is there special reason why my code does not allow me to programatically set a SelectionStart and SelectionLength in a RichTextBox ?

            text = System.IO.File.ReadAllText(path);
            prompterText.AppendText(File.ReadAllText(@path));
            prompterText.FontSize = textSize;
            prompterText.HorizontalAlignment = HorizontalAlignment.Center;
            prompterText.Focus();

            this.prompterText.SelectionStart = 0;
            this.prompterText.SelectionLength = 50;
            this.prompterText.SelectionBrush = System.Windows.Media.Brushes.Aqua ;

At the selection Start Line it tells me " RichTextBox does not contain a deffinition of SelectionStart and no extention method that accepts RichTextBox as a first argument could be found" .

Which is weird because I found alot of code examples that used the exact same line on RichTextBoxes .

    <ScrollViewer x:Name="scroller" Margin="0">
        <RichTextBox x:Name="prompterText" Margin="10" IsReadOnly="False"/>
    </ScrollViewer>

In the XAML code I set the IsReadOnly to false to be shure I have acces but still the same problem.

My intention is to have a text selection run in a prompter type window to set a specific reader speed .


Solution

  • RichTextBox SelectionStart property is available only in winforms. For WPF we need to use TextPointer to do the selection. Refer the below code.

    prompterText.AppendText("1111111111111111111111111111111111111111111111111111111111111111111111");           
    prompterText.HorizontalAlignment = HorizontalAlignment.Center;
    prompterText.Focus();
    TextPointer text = prompterText.Document.ContentStart;
    while (text.GetPointerContext(LogicalDirection.Forward) != TextPointerContext.Text)
    {
        text = text.GetNextContextPosition(LogicalDirection.Forward);
    }
    TextPointer startPos = text.GetPositionAtOffset(0);
    TextPointer endPos = text.GetPositionAtOffset(10); 
    prompterText.Selection.Select(startPos, endPos);
    this.prompterText.SelectionBrush = System.Windows.Media.Brushes.Aqua;