我想要突出显示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
} } }
答案 0 :(得分:2)
当前文本选择在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();
}