我需要在AvalonEdit中突出显示所有选定单词。我创建了一个HihglinghtingRule类的实例:
var rule = new HighlightingRule()
{
Regex = regex, //some regex for finding occurences
Color = new HighlightingColor {Background = new SimpleHighlightingBrush(Colors.Red)}
};
之后该怎么办? 感谢。
答案 0 :(得分:7)
要使用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
}
}
}
答案 1 :(得分:1)
我们必须确定是否有选择:
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
}
}
}