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

Asa*_*saf 9 wpf richtextbox

我看到了如何在RichTextBox类中设置WPF富文本框.

但我喜欢在Windows Forms中将其文本保存到数据库中.

string myData = richTextBox.Text;
dbSave(myData);
Run Code Online (Sandbox Code Playgroud)

我该怎么做?

Gav*_*ler 20

在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;
}
Run Code Online (Sandbox Code Playgroud)

  • +1:这对于一些如此基本的东西来说有点复杂.在大多数时间不需要控制开始和结束是有用的,我仍然期望.text或.context等. (2认同)