如何将WPF RichTextBox转换为字符串

12

我看到如何在 WPF 中设置富文本框,方法在 RichTextBox Class

但我想像之前在 Windows Forms 一样将其文本保存到数据库中。

string myData = richTextBox.Text;
dbSave(myData);

我该怎么做?


如果你只需要文本,为什么要使用RichTextBox呢?使用TextBox会不会更好呢? :) - Arcturus
1个回答

23

在MSDN的RichTextBox参考文献底部,有一个链接指向如何从RichTextBox提取文本内容

它将看起来像这样:

public string RichTextBoxExample()
{
    RichTextBox myRichTextBox = new RichTextBox();

    // Create a FlowDocument to contain content for the RichTextBox.
    FlowDocument myFlowDoc = new FlowDocument();

    // Add initial content to the RichTextBox.
    myRichTextBox.Document = myFlowDoc;

    // Let's pretend the RichTextBox gets content magically ... 

    TextRange textRange = new TextRange(
        // TextPointer to the start of content in the RichTextBox.
        myRichTextBox.Document.ContentStart, 
        // TextPointer to the end of content in the RichTextBox.
        myRichTextBox.Document.ContentEnd
    );

    // The Text property on a TextRange object returns a string
    // representing the plain text content of the TextRange.
    return textRange.Text;
}

2
+1:对于如此基本的东西来说,这有点复杂。控制开始和结束是有用的,但在大多数情况下并不需要,我仍然期望 .text 或 .context 等。 - Asaf
@Asaf 我认为这并不复杂,RichTextBox 不是一个纯文本文档。与 RichTextBox 相关联的有格式、样式等内容,因此具备基于对象的支持是有意义的。 - Gavin Miller
你可能是对的,但我在这里很快就会失去耐心:像设置文本、清除文本(=" ")或将字符串值放入函数中这样的基础知识都让我避之不及。这也许有道理,但一点也不友好。 - Asaf

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接