如何防止将某些类型的格式粘贴到 WPF RichTextBox 中
我想在 WPF RichTextBox 中允许一些简单的格式化命令,但不允许其他命令。
我创建了一个工具栏,允许用户应用粗体或斜体,并使用项目符号或编号列表。 (基本上,我只想支持适合博客或 wiki 的格式化命令。)
问题是用户可以执行剪切和粘贴操作,插入具有前景色和背景色的文本,以及其他类型的不允许的格式。这可能会导致严重的可用性问题,例如用户将白色文本粘贴到白色背景上。
有什么办法可以关闭这些高级格式化功能吗?如果没有,有没有办法可以拦截粘贴操作并删除我不想要的格式?
I want to allow some simple formatting commands within a WPF RichTextBox but not others.
I've created a toolbar that allows users to apply bold or italics, and use bulleted or numbered lists. (Basically, I only want to support the formatting commands that would be appropriate for a blog or wiki.)
The problem is that users can perform cut and paste operations that insert text with foreground and background colors, among other kinds of disallowed formatting. This can lead to nasty usability issues like users pasting white text onto a white background.
Is there any way to turn these advanced formatting features off? If not, is there a way I can intercept the paste operation and strip out the formatting I don't want?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以像这样拦截粘贴操作:
混乱的部分是保留一些但不是全部格式。 rtf 变量将是 RTF 格式的字符串,您可以使用第三方库来解析它,使用类似 DOM 的模式遍历树,并发出仅包含文本、粗体和斜体的新 RTF 。然后将其塞回到 e.SourceDataObject 或许多其他选项中(请参阅下面的文档)。
以下是
PastingHandler
文档:这是众多 RTF 解析器之一:
You can intercept the paste operation like this:
and the messy part is keeping some but not all of the formatting. The
rtf
variable will be a string in RTF format that you can use a third-party libary to parse, walk the tree using a DOM-like pattern, and emit new RTF with just text, bold and italics. Then cram that back intoe.SourceDataObject
or a number of other options (see the docs below).Here are
PastingHandler
docs:Here is one of many RTF parsers:
如果您想从粘贴的内容中删除所有格式,请使用以下代码(不是您所要求的,但可能对某人有用):
Here is the code if you wanted to strip all formatting from pasted content (Not what you asked, but may be usefull to someone):