【问题标题】:How to programatically set RichTextbox text and line color?如何以编程方式设置 RichTextbox 文本和线条颜色?
【发布时间】:2015-07-08 04:42:57
【问题描述】:

我正在使用this answer 以编程方式将彩色线条添加到我的 RichTextBox 的文本中。

我的RichTextBoxExtensions 课程与该解决方案中的课程完全相同。然后我有一个OutputMessage 类:

class OutputMessage
{
    private string _message;
    private Color _color;

    public string Message { get { return _message; } }
    public Color Color { get { return _color; } }

    public OutputMessage(string message, CodeDeployer.enums.OutputTypes ot)
    {
        _message = message;

        switch (ot)
        {
            case enums.OutputTypes.Success:
                _color = Color.Green;
                break;
            case enums.OutputTypes.Error:
                _color= Color.Red;
                break;
            case enums.OutputTypes.Warning:
                _color= Color.DarkOrange; 
                break;
            default:
                _color = Color.Black;
                break;
        }
    }
}

在我的表单上,我维护一个List<OutputMessage>,然后有一个方法会遍历List 并尝试将内容放入我的表单上的RichTextBox

private void foo()
{
    this.txtOutput = GetOutput();
    this.txtOutput.Text = GetOutput().Text;
}

private RichTextBox GetOutput()
{
    RichTextBox results = new RichTextBox();

    foreach (OutputMessage om in output)
        results.AppendText(om.Message, om.Color);

    return results;
}

如果我用第一行代码执行foo()txtOutput 根本不会改变。它只是一个空文本框。

如果我使用第二行代码执行foo()txtOutput 确实拥有我的List<OutputMessage> 中的所有文本,但是颜色丢失了。

如果我将GetOutput 更改为直接与表单上的控件交互,它会按预期工作。让它接受 RichTextBox 作为参数也可以。

谁能给我解释一下?我猜这与通过引用/值传递事物的方式有关,但我不明白。

【问题讨论】:

  • 您使用的是 windows 窗体或 wpf 控件,而不是 asp.net Web 控件,对吧?

标签: c# .net winforms


【解决方案1】:

RichTextBox.Text 属性是纯无格式文本。

Text 属性不返回有关应用于 RichTextBox 内容的格式设置的任何信息。要获取富文本格式 (RTF) 代码,请使用 Rtf 属性。

所以你应该尝试改用.Rtf 属性:

this.txtOutput.Rtf = GetOutput().Rtf;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多