Sword Art
Sword Art

Reputation: 29

C# WPF RichTextBox Scroll to text?

I'm working on alittle writing game and I encountered a problem. I have a richtextbox which contains one paragraph with alot of runs in it, and I want it to scroll to some run i have. I have a List object which contains all the inlines in the RTB, and the Select() Method doesn't work for some reason, maybe because it's a ready-only rtb. Any ideas for a way to scroll to selected word? My Code:

    private bool isKey = false;
    private Paragraph p;
    private List<Inline> inlineList;
    private int inlineIndex = 0, wpm = 0, wordIndex = 0, lineIndex = 0;
    private string[] words;
    public MainWindow()
    {
        InitializeComponent();
        p = new Paragraph();
        foreach (string s in words)
        {
            p.Inlines.Add(s);
            p.Inlines.Add(" ");
        }
        WordBox.Document.Blocks.Clear();
        WordBox.Document.Blocks.Add(p);
        inlineList = p.Inlines.ToList();
        inlineList[0].Background = Brushes.LightGray;
        this.Activate();
        InputBox.Focus();
    }
    //The Method I want to put the scrolling feature in:
    private void MoveWord()
    {
        if (inlineIndex + 2 < inlineList.Count)
        {
            inlineList[inlineIndex].Background = Brushes.Transparent;
            inlineIndex += 2;
            inlineList[inlineIndex].Background = Brushes.LightGray;
            WordBox.Selection.Select(inlineList[inlineIndex].ContentStart, inlineList[inlineIndex].ContentEnd);
        }
        else
            MessageBox.Show(wpm.ToString());
    }

For Example: the rtb contains: Hey Hello what's up word schnitzel hey

And I want it to scroll to the word "hey".

I've tried to use Select() method, which didn't work...

Upvotes: 0

Views: 971

Answers (1)

paparazzo
paparazzo

Reputation: 45106

Create runs and add runs (not inlines)
Save a reference to the runs (e.g. a List)
And then just call Runs[x].BringIntoView()
Have not tested on RTB but I have done this with FlowDocument and FlowDocumentViewer

BringIntoView

Upvotes: 2

Related Questions