在AvalonEdit中选择高亮显示单词的所有实例
本文关键字:实例 单词 显示 AvalonEdit 选择 高亮 | 更新日期: 2023-09-27 18:22:21
我想在AvalonEdit中突出显示所选(突出显示)文本的所有实例。VS2010做到了这一点,它是一个方便的功能。我知道我需要按照下面的代码实现DocumentColorizingTransformer,但不知道如何从文档中获得选定的文本。选择信息在"CurrentContext"中不可用。
下面的代码查找"AvalonEdit"的所有实例。如何查找所选(高亮显示)文本的所有实例。
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上可用,因此您可以从ColorizeAvalonEdit类中使用它。
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.TextView.LineTransformers.Add(new ColorizeAvalonEdit(textEditor));
textEditor.TextArea.SelectionChanged += textEditor_TextArea_SelectionChanged;
void textEditor_TextArea_SelectionChanged(object sender, EventArgs e)
{
this.textEditor.TextArea.TextView.Redraw();
}