A way to overcome RichTextBox's limitations?

强颜欢笑 提交于 2021-02-11 15:24:07

问题


I am developing an app using WinForms and the RichTextBox control. This control allows different changes to the RTF formatting using a property to change the font of the selected text. I have a button to toggle bold on the text:

richTextBoxEditor.SelectionFont = new Font(richTextBoxEditor.SelectionFont,
    richTextBoxEditor.SelectionFont.Style ^ FontStyle.Bold);

My other buttons (italic, underline) have identical code except for the FontStyle.Bold part which is changed for the appropriate formatting.

Now the problem with this is, if I write "Hello World" and change the "Hello" to say italic, and then I try to change the whole "Hello World" to bold, "Hello" loses its italic. I understand why it does this (because the enum for the whole selection is empty so when I toggle bold, the italic flag remains to 0), but I am trying to find a way to overcome this. I can't think of anything short of going character by character and changing style individually.

Would you guys have any better idea?

Thanks.


回答1:


It sounds like character by character is your safest bet. It doesn't seem like a significant problem unless you're creating a full-blown word processor.

The other alternative is to break up selections based on current styling. So, if someone selects a larger region than a style is applied to, you need to break up the selection into two parts: the part that completely overlaps the styled area and the part that does not overlap the styled area at all. You'll need to go character by character to find out where to break up the selections, but at least you won't have to necessarily apply styles to every individual character.



来源:https://stackoverflow.com/questions/3089866/a-way-to-overcome-richtextboxs-limitations

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!