RichTextBox (WPF) does not have string property "Text"
202,444
Solution 1
to set RichTextBox text:
richTextBox1.Document.Blocks.Clear();
richTextBox1.Document.Blocks.Add(new Paragraph(new Run("Text")));
to get RichTextBox text:
string richText = new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd).Text;
Solution 2
The WPF RichTextBox has a Document
property for setting the content a la MSDN:
// Create a FlowDocument to contain content for the RichTextBox.
FlowDocument myFlowDoc = new FlowDocument();
// Add paragraphs to the FlowDocument.
myFlowDoc.Blocks.Add(new Paragraph(new Run("Paragraph 1")));
myFlowDoc.Blocks.Add(new Paragraph(new Run("Paragraph 2")));
myFlowDoc.Blocks.Add(new Paragraph(new Run("Paragraph 3")));
RichTextBox myRichTextBox = new RichTextBox();
// Add initial content to the RichTextBox.
myRichTextBox.Document = myFlowDoc;
You can just use the AppendText
method though if that's all you're after.
Hope that helps.
Solution 3
Using two extension methods, this becomes very easy:
public static class Ext
{
public static void SetText(this RichTextBox richTextBox, string text)
{
richTextBox.Document.Blocks.Clear();
richTextBox.Document.Blocks.Add(new Paragraph(new Run(text)));
}
public static string GetText(this RichTextBox richTextBox)
{
return new TextRange(richTextBox.Document.ContentStart,
richTextBox.Document.ContentEnd).Text;
}
}
Solution 4
There is no Text
property in the WPF RichTextBox control. Here is one way to get all of the text out:
TextRange range = new TextRange(myRTB.Document.ContentStart, myRTB.Document.ContentEnd);
string allText = range.Text;
Solution 5
string GetString(RichTextBox rtb)
{
var textRange = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd);
return textRange.Text;
}
Author by
Admin
Updated on July 27, 2022Comments
-
Admin almost 2 years
I am trying to set/get the text of my RichTextBox, but Text is not among list of its properties when I want to get test.Text...
I am using code behind in C# (.net framework 3.5 SP1)
RichTextBox test = new RichTextBox();
cannot have
test.Text(?)
Do you know how come it can be possible ?
-
kamranicus almost 14 yearsThis is WPF, not Win Forms.
-
alvinmeimoun over 9 yearsContructor 'Run' has 0 parameter(s) but is invoked with 1 argument(s) , same for Paragraph
-
Marty_in_a_Box about 8 yearsBest answer that i could find so far :) Here my code if you want to paste the Length in another Textbox in a GUI:
rtxb_input.SelectAll();
txb_InputLength.Text = rtxb_input.Selection.Text.Length.ToString();
-
Dragomok over 7 years@alvinmeimoun Actually,
Paragraph()
had aParagraph(Inline)
overload at least since .NET 3.5 (andRun(string)
was also valid - it's even in the example). -
Admin over 6 yearswhy so complicated?
-
Matheus Miranda about 6 yearsHow to add
FontFamily
in paragraph ?