问题描述
现在我已经用了太多时间长了,想弄清楚一个问题,这是我没有想到会那么难
I have now used way too long time, trying to figure out a problem, which I didn't think would be that hard.
下面是处理:
我使用C#和WPF写一个小的应用程序。
I am writing a small application using C# and WPF.
我有一个包含一个FlowDocument的一个RichTextBox。
I have a RichTextBox containing a FlowDocument.
我添加了一个小的文本框,下面我RichTextBox的一个按钮。
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.
然后在RichTextBox将跳转到这个词第一次出现。
The richtextbox will then jump to the first occurrance of that word.
就足够了,它只是跳转到正确的路线 - 它也可以选择,高亮显示或按字将光标 - 随便什么都行,只要RichTextBox的滚动字
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.
推荐答案
这应该做的工作:
public bool DoSearch(RichTextBox richTextBox, string searchText, bool searchNext)
{
TextRange searchRange;
// Get the range to search
if(searchNext)
searchRange = new TextRange(
richTextBox.Selection.Start.GetPositionAtOffset(1),
richTextBox.Document.ContentEnd);
else
searchRange = new TextRange(
richTextBox.Document.ContentStart,
richTextBox.Document.ContentEnd);
// Do the search
TextRange foundRange = FindTextInRange(searchRange, searchText);
if(foundRange==null)
return false;
// Select the found range
richTextBox.Selection.Select(foundRange.Start, foundRange.End);
return true;
}
public TextRange FindTextInRange(TextRange searchRange, string searchText)
{
// Search the text with IndexOf
int offset = searchRange.Text.IndexOf(searchText);
if(offset<0)
return null; // Not found
// Try to select the text as a contiguous range
for(TextPointer start = searchRange.Start.GetPositionAtOffset(offset); start != searchRange.End; start = start.GetPositionAtOffset(1))
{
TextRange result = new TextRange(start, start.GetPositionAtOffset(searchText.Length);
if(result.Text == searchText)
return result;
}
return null;
}
的
原因在FindTextInRangeUnfortunately的range.Text的为()循环剔除非文本字符,所以在一些情况下,偏移量由的IndexOf计算会稍微过低。
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.
这篇关于做一个简单的搜索功能,使光标跳到(或突出),该搜索词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!