Skip to main content
 首页 » 编程设计

c#之富文本框属性问题

2024年02月23日14jpfss

<RichTextBox AcceptsTab="True" ForceCursor="True" IsDocumentEnabled="True" TextChanged="ContentChanged" Name="TextContent"/> 

在 C# 文件中,我无法获取 Rich Textbox 的 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?)  

请给我建议。

请您参考如下方法:

通常,您需要使用 Blocks属性(property)。但是,如果您使用 FlowDocument用于表示 RichTextBox 内容,然后您可以使用 Document 访问文本属性(property)。

比如写内容:

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类(class)。下一段代码将检索所有文本内容:

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