为什么当试图在richTextBox中为多个部分的文本着色时,它根本没有着色

本文关键字:文本 richTextBox 个部 为什么 | 更新日期: 2023-09-27 17:54:59

它将为一部分文本上色。

void lvnf_SelectedIndexChanged(object sender, EventArgs e)
{
    if (ListViewCostumControl.lvnf.SelectedItems.Count > 0)
    {
        string word = textBox1.Text;
        string[] test = word.Split(',');
        foreach (string myword in test)
        {
            richTextBox1.Text = File.ReadAllText(ListViewCostumControl.lvnf.Items[ListViewCostumControl.lvnf.SelectedIndices[0]].Text);
            FileInfo fi = new FileInfo(ListViewCostumControl.lvnf.Items[ListViewCostumControl.lvnf.SelectedIndices[0]].Text);
            HighlightPhrase(richTextBox1, myword, Color.Yellow);
            if (myword == "Form1")
            {
                break;
            }
        }
    }
}

static void HighlightPhrase(RichTextBox box, string phrase, Color color)
{
    int pos = box.SelectionStart;
    string s = box.Text;
    for (int ix = 0; ; )
    {
        int jx = s.IndexOf(phrase, ix, StringComparison.CurrentCultureIgnoreCase);
        if (jx < 0) { break; }
        box.SelectionStart = jx;
        box.SelectionLength = phrase.Length;
        box.SelectionColor = color;
        ix = jx + 1;
    }
    box.SelectionStart = pos;
    box.SelectionLength = 0;
}

当我添加这个break部分时:

if (myword == "Form1")
{
    break;
}

它的工作,它将颜色在richTextBox的所有地方与Form1。但是,如果我删除这个break部分,它应该颜色在richTextBox的文本是从字符串数组变量test存在的所有地方。

In test i have: Form1,form2,hi,44

但这根本不是着色。

为什么当试图在richTextBox中为多个部分的文本着色时,它根本没有着色

当您删除if (myword == "Form1") break;部分时,代码几乎变成:

foreach (string myword in test)
            {
                richTextBox1.Text = ......;
                HighlightPhrase(richTextBox1, myword, Color.Yellow);                       
             }

在你的例子中,因为你的测试字符串是Form1 form2 hi 44,它变成了:

 richTextBox1.Text = ......;
 HighlightPhrase(richTextBox1, "Form1", Color.Yellow);
 richTextBox1.Text = ......;
 HighlightPhrase(richTextBox1, "form2", Color.Yellow);
 richTextBox1.Text = ......;
 HighlightPhrase(richTextBox1, "hi", Color.Yellow);
 richTextBox1.Text = ......;
 HighlightPhrase(richTextBox1, "44", Color.Yellow);

正如您所看到的,文本属性不断变化,因此格式被重置(或在某些情况下应用于整个字符串)。

做一些假设,我会把你的代码改为:

if (ListViewCostumControl.lvnf.SelectedItems.Count > 0)
        {
            var selectedText = ListViewCostumControl.lvnf.Items[ListViewCostumControl.lvnf.SelectedIndices[0]].Text;
            richTextBox1.Text = File.ReadAllText(selectedText);
            FileInfo fi = new FileInfo(selectedText);  //not used!
            string word = textBox1.Text;
            string[] test = word.Split(',');
            foreach (string myword in test)
            {                    
                HighlightPhrase(richTextBox1, myword, Color.Yellow);
            }
          }