我正在用 WPF(.NET 6)中的 RichTextBox 替換 TextBox,并且很難移植搜索代碼。我已經使用這些方法嘗試了 TextRange 和 TextPointer GetOffset(),但沒有任何效果。但是,下面的代碼有效。這對我來說似乎是一種解決方法,也許你們中的一個人覺得它有幫助或知道更好的方法。
var textRange = new TextRange(flowDocument.ContentStart, flowDocument.ContentEnd);
var text = textRange.Text;
int startIndex = 0;
// Set the start index to the offset
if (StartPosition != null)
{
startIndex = textRange.Start.GetOffsetToPosition(StartPosition);
}
SearchResultValue searchResult;
var result = text.IndexOf(SearchPattern, startIndex, comparison);
// Any result value of 0 or greater indicates a hit
if (result >= 0)
{
// Hit
var selectionStart = textRange.Start.GetPositionAtOffset(result);
// Iterate over the index positions until the end of the search pattern. Is there a better way of doing it?
var currentSelection = textRange.Start.GetPositionAtOffset(result);
for (int run = 0; run < SearchPattern.Length; run )
{
currentSelection = currentSelection.GetNextInsertionPosition(LogicalDirection.Forward);
}
var selectedRange = new TextRange(selectionStart, currentSelection);
searchResult = new SearchResultValue(true, selectedRange);
}
else
{
// No hit
searchResult = new SearchResultValue(false, null);
}
return searchResult;
/// <summary>
/// Specifies the result of the search operation
/// </summary>
/// <param name="Successful">true if any content has been found</param>
/// <param name="start">the start index</param>
/// <param name="length">the length</param>
internal record struct SearchResultValue(bool Successful, TextRange ? Selection);
有更好的方法嗎?我花時間瀏覽 MSDN 和其他資源,這是我能找到的最好的。但我也是這個控制元件的新手。
謝謝!
uj5u.com熱心網友回復:
我終于可以解決了。唯一的解決方案似乎是決議每個段落并搜索每個段落中的文本。為了讓您了解我的意思:
internalSearchPosition 是一個私有 TextPointer 實體并存盤最新命中。SearchResultValue 只是我的視圖模型邏輯的回傳值。整個代碼太長了,不適合發布,但這是搜索功能的核心。
while (currentBlock != null)
{
var paragraph = currentBlock as Paragraph;
if (paragraph != null)
{
//
// Get the range of the paragraph content and search for the pattern
//
var paragraphRange = new TextRange(internalSearchPosition, paragraph.ContentEnd);
var paragraphText = paragraphRange.Text;
int result = paragraphText.IndexOf(searchPattern, comparison);
if (result >= 0)
{
//
// Hit. Build the search result and leave the for each loop
//
var startSelection = paragraph.ContentStart.GetPositionAtOffset(result);
var endSelection = startSelection.GetPositionAtOffset(searchPattern.Length 1);
searchResult = new SearchResultValue(true, new TextRange(startSelection,endSelection));
// Save the current position
internalSearchPosition = endSelection;
break;
}
}
// Go to the next block or leave the loop when NextBlock is null (end of paragraphs). Also reset the internal search position if required.
currentBlock = currentBlock.NextBlock;
if (currentBlock != null)
{
internalSearchPosition = currentBlock.ContentStart;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/492189.html
