开发者

C#: Inserting text in a RichTextBox causes the formatting to be lost

I am trying to insert text at runtime in a RichTextBox, but when I do so, all the formatting that was previously present is lost.

From what I understand, the formatting is lost because I'm overwriting the "Text" property of the RichTextBox when my KeyPress event is called:

(...)
Text = Text.Insert(SelectionStart, MyText);
e.Handled = true;

On a side-note, my RichTextBox's height is calculated at run-time depending on its content.

I am forced to insert text in the RTB, or else the content would not be properly displayed following its resizing (i.e: For some reason, the first line of the RTB would appear to have scrolled up and can only be seen once the control has lost focus... See: C#: How to prevent a textbox' content from being scrolled up on Enter?).

Is there any way to insert text in a RichTextBox, while also kee开发者_StackOverflowping all the previous formatting intact ?

Thanks, your help is much appreciated.


I believe the issue is caused by complete text reset (Text = ...). Try using something like:

SelectionLength = 0; // not sure about this one
SelectedText = MyText;


Try AppendText instead, followed by ScrollToCaret.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜