我真的不知道应该从哪里开始。
我有一个带有 RichTextBox
的 WPF 应用程序,其中包含使用 FlowDocument
的文本负载,该文本会根据用户的选择而变化。
我需要一种方法,用户可以通过该方法在 TextBox
中输入单词,并且如果找到该单词的每个实例,则将在相邻的 RichTextBox
中突出显示>。 http://kentb.blogspot.com/2009/06/search-and-highlight-text-in-arbitrary.html这个想法很完美,但我对如何使用 RichTextBox
将其应用到我的应用程序一无所知。
提前谢谢您!
最佳答案
您尝试过使用正则表达式吗?
类似于:
private void searchButton_Click(object sender, EventArgs e)
{
//Select all text and bring it back to default color values so you
//can make a new search selection
richTextBox1.SelectAll();
richTextBox1.SelectionColor = System.Drawing.Colors.Black;
//Deselect all text to ready selections
richTextBox1.DeselectAll();
//Create a MatchList variable and initialize it to all matches
//within the RichTextBox. Add a using statement of
//System.Text.RegularExpressions
Color evenColor = Color.Red;
Color oddColor = Color.Blue;
MatchCollection matches = Regex.Matches(richTextBox1.Text, searchTextBox.Text);
//Apply color to all matching text
int matchCount = 0;
foreach (Match match in matches)
{
richTextBox1.Select(match.Index, match.Length);
//richTextBox1.SelectionColor = System.Drawing.Color.Red;
richTextBox1.SelectionColor =
matchCount++ % 2 == 0 ? evenColor : oddColor;
}
}
只要您的盒子中不需要同时使用多种颜色,此方法就有效。我相信,通过一些额外的逻辑,您也可以将其纳入其中。
编辑:在 WPF 中不起作用。持续关注 WinForms。
关于c# - 搜索 RichTextBox 并突出显示该特定单词的所有实例的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8772308/