简体   繁体   中英

WPF reading and writing RichTextBox text

I am quite new to WPF and have come across a problem.

I have a rich text box and I set it's text. Then, whenever the rich texbox text changes (using event handler), I need to check if it was equal to the origional text.

But, even when the text hasn't changed, the code says it has due to a new line appearing when reading the text.

This is basically what I am doing: (a simiplified version showing the problem)

//Create a new text box
RichTextBox r = new RichTextBox();

//Write Text "Hello World" to the rich text box
r.Document.Blocks.Clear();
r.Document.Blocks.Add(new Paragraph(new Run("Hello World")));

//Read Text "Hello World" from rich text box
string textBoxText = new TextRange(r.Document.ContentStart, r.Document.ContentEnd).Text;
Console.WriteLine("\"" + textBoxText + "\"");

I would expect to see "Hello World" in the console, but instead it gives:

"Hello World
"

Because there is a new line after this, it causes problems in my code. Is there a better way of reading and writing the RichTextBox to avoid this??

I have decided to use a Windows Forms RichTextBox within the WPF window instead of the standard WPF RichTextBox.

It's a bit trickier to use with xaml so i'm mainly setting its properties when the window is opened in the code-behind.

It has solved all of my problems so far.

More Information:

https://msdn.microsoft.com/en-us/library/ms751761(v=vs.110).aspx

https://www.simple-talk.com/dotnet/.net-framework/mixing-wpf-and-winforms/

(I won't mark this as the answer, as it doesn't solve the problem if you want to use a WPF RichTextBox and not WinForms)

Edit: Actually, it's best to avoid this method as the WinForms control is drawn above all WPF controls. This stops me from using drop down menus in wpf. ... Still looking for answer!!!

Edit:

I tried to use this answer to draw my wpf drop down menus above the winforms RichTextBox. It worked, but the alignment went wrong.

Now, I have abandoned both WPF and WinForms RichTextBox and have gone with AvalonEdit (which is amazing). It was origionally made for a code editor but works well for any kind of RichTextBox replacement.

I used a mixture of this and this for changing the colour of parts of the text.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM