C#:在 RichTextBox 中插入文本会导致格式丢失
我试图在运行时在 RichTextBox 中插入文本,但是当我这样做时,以前存在的所有格式都会丢失。
据我了解,格式丢失了,因为当我的 KeyPress 事件被调用时,我覆盖了 RichTextBox 的“Text”属性:
(...)
Text = Text.Insert(SelectionStart, MyText);
e.Handled = true;
顺便说一句,我的 RichTextBox 的高度是在运行时计算的 -时间取决于其内容。
我被迫在 RTB 中插入文本,否则内容在调整大小后将无法正确显示(即:由于某种原因,RTB 的第一行似乎已向上滚动并且可以仅在控件失去焦点后可见...请参阅:C#:如何防止文本框的内容在 Enter 时向上滚动?)。
有没有什么方法可以在 RichTextBox 中插入文本,同时保持所有以前的格式不变?
谢谢,非常感谢您的帮助。
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 keeping all the previous formatting intact ?
Thanks, your help is much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为该问题是由完全文本重置 (
Text = ...
) 引起的。尝试使用类似的东西:I believe the issue is caused by complete text reset (
Text = ...
). Try using something like:尝试改为 AppendText,后跟 < a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.textboxbase.scrolltocaret.aspx" rel="nofollow">ScrollToCaret。
Try AppendText instead, followed by ScrollToCaret.