WPF RichTexBox中的选定文本格式 [英] Selected Text Formatting in WPF RichTexBox
问题描述
我正在尝试在WPF RichTextBox中实现以编程方式选择(使用正则表达式)的文本格式.用例只是一个WPF RichTextBox,用户可以在其中键入文本.但是,为了提高或加快可读性,我想在键入文本时合并一些自动格式设置.
I am trying to implement programmatically selected (using regex) text formatting in a WPF RichTextBox. The use case is simply a WPF RichTextBox in which the user types text. However, to improve or accelerate readability i want to incorporate some automatic formatting as the text is typed.
以下代码来自如何选择来自RichTextBox的文本,然后为它着色?正是我想要做的.但是,据我所知,此代码用于WinForms RichTextBox:
The following code from How to select text from the RichTextBox and then color it? is exactly what i am trying to do. However, as far as i can tell this code is for a WinForms RichTextBox:
public void ColourRrbText(RichTextBox rtb)
{
Regex regExp = new Regex(@"\b(For|Next|If|Then)\b");
foreach (Match match in regExp.Matches(rtb.Text))
{
rtb.Select(match.Index, match.Length);
rtb.SelectionColor = Color.Blue;
}
}
我尝试将其转换如下:
public static void ColorSpecificText(RichTextBox rtb)
{
TextRange textRange = new TextRange(rtb.Document.ContentEnd, rtb.Document.ContentEnd);
Regex regex = new Regex(@"\b(For|Next|If|Then)\b");
foreach (Match match in regex.Matches(textRange.Text))
{
textRange.Select(match.Index, match.Length); // <--- DOESN'T WORK
textRange.SelectionColor = Color.Blue; // <--- DOESN'T WORK
}
}
但是,我一直坚持如何将"match.Index,match.Length"和"SelectionColor"语法转换为WPF RichTextBox知道如何处理的东西.我搜索了其他帖子,但大多数似乎也是针对WinForms RichTextBox,而不是WPF.任何指导将不胜感激.
However, i am stuck on how to convert the "match.Index, match.Length" and the "SelectionColor" syntax to something that the WPF RichTextBox knows how to handle. I have searched other posts, but most also seem to be for WinForms RichTextBox, not WPF. Any guidance would be greatly appreciated.
推荐答案
这是语法:
TextRange textRange = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd);
textRange.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Black);
Regex regex = new Regex(@"\b(For|Next|If|Then)\b");
int i = 0;
foreach (Match match in regex.Matches(textRange.Text))
{
var wordStartOffset = textRange.Start.GetPositionAtOffset(i + match.Index);
var wordEndOffset = textRange.Start.GetPositionAtOffset(i + match.Index + match.Length);
var wordRange = new TextRange(wordStartOffset, wordEndOffset);
wordRange.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.LightBlue);
i += 4; // could be something else
}
尽管由于您的策略可能无法正确突出显示.恐怕字符串索引不足以创建正确的TextPointer. +4用于跳过格式设置开销,因此如果存在其他格式,它可能无法正常工作.
Although it may not highlight correctly because of your strategy. I'm afraid string index is not enough to create the proper TextPointer. +4 is used to skip formatting overheads, that's why it may not work if other formattings are present.
这篇关于WPF RichTexBox中的选定文本格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!