如何将WPF富文本框转换为字符串

时间:2010-11-08 15:37:41

标签: wpf richtextbox

我了解了如何在 WPF 中设置RichTextBox Class富文本框。

然而,我喜欢在Windows Forms中将其文本保存到数据库中。

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

我该怎么做?

1 个答案:

答案 0 :(得分:18)

在MSDN RichTextBox参考的底部,有How to Extract the Text Content from a 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;
}