【问题标题】:Rich Text box Properties problem富文本框属性问题
【发布时间】:2011-03-14 06:36:52
【问题描述】:
<RichTextBox AcceptsTab="True" ForceCursor="True" IsDocumentEnabled="True" TextChanged="ContentChanged" Name="TextContent"/>

在 C# 文件中,我无法获取富文本框的 Text 属性。 我正在努力做到这一点;

TextContent.Text= "hello"

但它给出了编译时错误。

'System.Windows.Controls.RichTextBox' does not contain a definition for 'Text' and no extension method 'Text' accepting a first argument of type 'System.Windows.Controls.RichTextBox' could be found (are you missing a using directive or an assembly reference?) 

请给我建议。

【问题讨论】:

  • 你需要用到 Document 属性,看这里:stackoverflow.com/questions/957441/…
  • 您真的在尝试读取或写入内容吗?因为您在示例中询问如何获取并尝试设置...无论如何,我在下面的答案中添加了示例。

标签: c# wpf richtextbox


【解决方案1】:

通常,您需要使用Blocks 属性。但是,如果您使用FlowDocument 表示RichTextBox 内容,那么您可以使用Document 属性访问文本。

比如写内容:

XAML:

<RichTextBox Name="rtb">
</RichTextBox>

代码:

FlowDocument contentForStoring =
    new FlowDocument(new Paragraph(new Run("Hello, Stack Overflow!")));
rtb.Document = contentForStoring;

要阅读内容,您只需访问Document 属性:

FlowDocument yourStoredContent = rtb.Document;

如果您只需要获取文本,您有更简单的方法 - TextRange 类。接下来的代码将检索所有文本内容:

TextRange storedTextContent =
    new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd);
string yourText = storedTextContent.Text;

【讨论】:

    【解决方案2】:

    如果您想从富文本框中检索文本,请使用此代码,

    string content = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd).Text;
    

    【讨论】:

      猜你喜欢
      • 2011-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-29
      • 2011-07-26
      • 1970-01-01
      • 1970-01-01
      • 2010-11-11
      相关资源
      最近更新 更多