制作一个简单的搜索功能,使光标跳转到(或突出显示)要搜索的单词
我现在已经花了很长时间来试图解决一个问题,我认为这不会那么难。
事情是这样的:
我正在使用 C# 和 WPF 编写一个小型应用程序。
我有一个包含 FlowDocument 的 RichTextBox。
我在 Richtextbox 下方添加了一个小文本框和一个按钮。
然后,用户输入他/她想要搜索的单词,并按下按钮。
然后,richtextbox 将跳转到该单词第一次出现的位置。
只要跳到正确的行就足够了 - 它还可以选择、突出显示或将光标放置在单词旁边 - 任何事情都可以,只要 richTextBox 滚动到单词即可。
继续按该按钮,将跳转到下一个出现的单词,依此类推,直到文档末尾。
正如我所说 - 我认为这是一项简单的任务 - 然而我在解决这个问题时遇到了严重的问题。
I have now used way too long time, trying to figure out a problem, which I didn't think would be that hard.
Here is the deal:
I am writing a small application using C# and WPF.
I have a RichTextBox containing a FlowDocument.
I have added a small textbox and a button below my richtextbox.
The user then types in the word he/she wishes to search for, and presses the button.
The richtextbox will then jump to the first occurrance of that word.
it is enough that it just jumps to the correct line - it can also select, highlight or place the cursor by the word - anything will do, as long as the richTextBox is scrolled to the word.
Continuing to press the button, will then jump to the next occurance of the word, and so on so forth, till the end of the document.
As I said - I thought it to be a simple task - however I am having serious problems figuring this out.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这应该可以完成工作:
FindTextInRange 中 for() 循环的原因不幸的是 range.Text 会去除非文本字符,因此在某些情况下由 IndexOf 计算的偏移量会稍微太低。
This should do the job:
The reason for the for() loop in FindTextInRangeUnfortunately the range.Text strips out non-text characters, so in some cases the offset computed by IndexOf will be slightly too low.
我使用了不同的方法。
使用文本框设置关键字;这会在单击按钮时搜索关键字。
找到关键字;突出显示它并关注该关键字。
我唯一无法实现的就是返回到第一个搜索结果
I have used a Different Approach.
Using a TextBox to Set the Keyword; this Searches for the KeyWord on Button Click.
Finds the Keyword; Highlighs it and Focuses on that KeyWord.
The only thing I couldn't achieve yet is to return to the 1st Search Result
这是一个变体,它将找到最接近插入符位置的匹配项。
如果您想突出显示匹配项,那么只需将此方法更改为 void 并在找到匹配项时执行此操作即可:
This is a variant that will find the match closest to the Caret position.
If you want to highlight the match then it'd be as simple as changing this method to void and doing this when you found the match: