2011-03-14 60 views
1
<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?) 

請給我建議。

+0

和錯誤消息是... – 2011-03-14 06:38:11

+1

您需要使用文檔屬性,看看這裏:http://stackoverflow.com/questions/957441/richtextbox-wpf-does-not-have-string-property-text – 2011-03-14 06:43:24

+0

你實際上是試圖讀取或寫入內容?因爲你問如何獲得並試圖設置例子......無論如何,我在下面的答案中添加了一些例子。 – 2011-03-14 17:38:01

回答

4

通常,您需要使用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; 
0

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