[英]Highlight all occurrences of selected word in AvalonEdit
我需要在 AvalonEdit 中突出顯示所有出現的選定單詞。 我創建了一個 HihglinghtingRule 類的實例:
var rule = new HighlightingRule()
{
Regex = regex, //some regex for finding occurences
Color = new HighlightingColor {Background = new SimpleHighlightingBrush(Colors.Red)}
};
之后我該怎么辦? 謝謝。
要使用該HighlightingRule
,您必須創建突出顯示引擎的另一個實例( HighlightingColorizer
等)
編寫一個突出顯示您的話的DocumentColorizingTransformer
更容易、更有效:
public class ColorizeAvalonEdit : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
int lineStartOffset = line.Offset;
string text = CurrentContext.Document.GetText(line);
int start = 0;
int index;
while ((index = text.IndexOf("AvalonEdit", start)) >= 0) {
base.ChangeLinePart(
lineStartOffset + index, // startOffset
lineStartOffset + index + 10, // endOffset
(VisualLineElement element) => {
// This lambda gets called once for every VisualLineElement
// between the specified offsets.
Typeface tf = element.TextRunProperties.Typeface;
// Replace the typeface with a modified version of
// the same typeface
element.TextRunProperties.SetTypeface(new Typeface(
tf.FontFamily,
FontStyles.Italic,
FontWeights.Bold,
tf.Stretch
));
});
start = index + 1; // search for next occurrence
}
}
}
我們必須決定是否有選擇:
TextEditor.TextArea.SelectionChanged += (sender, args) =>
{
if (string.IsNullOrWhiteSpace(TextEditor.SelectedText))
{
foreach (var markSameWord in TextEditor.TextArea.TextView.LineTransformers.OfType<MarkSameWord>().ToList())
{
TextEditor.TextArea.TextView.LineTransformers.Remove(markSameWord);
}
}
else
{
TextEditor.TextArea.TextView.LineTransformers.Add(new MarkSameWord(TextEditor.SelectedText));
}
};
這是DocumentColorizingTransformer
類:
public class MarkSameWord : DocumentColorizingTransformer
{
private readonly string _selectedText;
public MarkSameWord(string selectedText)
{
_selectedText = selectedText;
}
protected override void ColorizeLine(DocumentLine line)
{
if (string.IsNullOrEmpty(_selectedText))
{
return;
}
int lineStartOffset = line.Offset;
string text = CurrentContext.Document.GetText(line);
int start = 0;
int index;
while ((index = text.IndexOf(_selectedText, start, StringComparison.Ordinal)) >= 0)
{
ChangeLinePart(
lineStartOffset + index, // startOffset
lineStartOffset + index + _selectedText.Length, // endOffset
element => element.TextRunProperties.SetBackgroundBrush(Brushes.LightSkyBlue));
start = index + 1; // search for next occurrence
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.