将前缀设置为粗体并保留下划线

时间:2012-12-19 17:29:09

标签: c# winforms richtextbox rtf

我正在尝试将我的标题设置为Bold并保留下划线。例如:

TitleScreenshot

代码使所有行都变粗。从上图中可以看出,只有标题应该是粗体。如何修复代码以匹配图像?

        List<string> titles = new List<string> { "Basic Metabolic Panel", "Complete Blood Count", "Comprehensive Metabolic Panel" };
        List<string> bodies = new List<string> { " : Collected: 8/20/2012 5:45:00 PM", " : Collected: 8/20/2012 5:45:00 PM", " : Collected: 8/17/2012 4:18:00 AM" };


        for (int i = 0; i < titles.Count; i++)
        {
            string labName = titles[i];
            string collectionDate = bodies[i];
            int oldTextEndPoint = rtb.Text.Length;

            rtb.Text += labName + collectionDate + Environment.NewLine;

            rtb.Select(oldTextEndPoint, labName.Length + collectionDate.Length);
            rtb.SelectionFont = new Font(rtb.Font, rtb.SelectionFont.Style | FontStyle.Underline);

            rtb.Select(oldTextEndPoint, labName.Length);
            rtb.SelectionFont = new Font(rtb.Font, rtb.SelectionFont.Style | FontStyle.Bold);
        }   

2 个答案:

答案 0 :(得分:1)

问题是您正在将SelectionFont设置为基于RTB默认字体的新字体 - 而不是基于当前的SelectionFont。

尝试将其更改为:

rtb.Select(oldTextEndPoint, labName.Length + collectionDate.Length);
rtb.SelectionFont = new Font(rtb.SelectionFont, rtb.SelectionFont.Style | FontStyle.Underline);

rtb.Select(oldTextEndPoint, labName.Length);
rtb.SelectionFont = new Font(rtb.SelectionFont, rtb.SelectionFont.Style | FontStyle.Bold);

编辑1:

我刚刚使用以下代码创建了一个简单的Windows应用程序,它同时使用粗体和下划线:

rtb.Text = "abcdefghijklmnopqrstuvwxyz";
rtb.Select(3, 10);
rtb.SelectionFont = new Font(rtb.SelectionFont, rtb.SelectionFont.Style | FontStyle.Bold);
rtb.Select(3, 5);
rtb.SelectionFont = new Font(rtb.SelectionFont, rtb.SelectionFont.Style | FontStyle.Underline);

答案 1 :(得分:0)

更改

rtb.Text += labName + collectionDate + Environment.NewLine;

rtb.AppendText(labName + collectionDate + Environment.NewLine);

并且事情正常......