【发布时间】:2020-04-17 06:04:43
【问题描述】:
我正在尝试在 WPF RichTextBox 中以编程方式选择(使用正则表达式)文本格式。用例只是一个 WPF RichTextBox,用户在其中键入文本。但是,为了提高或加速可读性,我想在输入文本时加入一些自动格式。
How to select text from the RichTextBox and then color it? 的以下代码正是我想要做的。但是,据我所知,此代码适用于 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。任何指导将不胜感激。
【问题讨论】:
-
要使用单词边界,请使用逐字字符串文字,或双反斜杠,
@"\b(For|Next|If|Then)\b" -
感谢@Wiktor。你是对的,需要@。但这并不能解决 match.index 的问题,匹配长度会产生错误代码“无法从 int 转换为 'System.Windows.Documents.TextPointer'”。
-
Thaty 已经不是正则表达式问题。请修改问题。
textRange.Select期望什么类型的价值?SelectionColor似乎期待System.Drawing.Color。但这种可能性会影响整个组件文本,而不仅仅是其中的一部分。 -
我同意 - 这不是正则表达式问题。 textRange.Select 取两个 TextPointers。我的问题是使用 TextPointers 指定 match.index 和 match.length 的语法是什么。
-
@scorpiotomse 如果某个答案解决了您的问题,请点击勾选标记让其他人知道此问题已解决。
标签: wpf formatting richtextbox