手动设置 Xaml 属性时在 RichTextBox 中显示花括号 [英] Display curly braces in RichTextBox when manually setting Xaml property

查看:53
本文介绍了手动设置 Xaml 属性时在 RichTextBox 中显示花括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在开发适用于 Windows Phone 的 Twitter 应用程序,其中 - 通过自定义 DependencyProperty - 每个 RichTextBox 绑定到推文的文本(包括以编程方式生成的带有所有文本的 Run 元素).这工作得很好,直到文本中有大括号 {} .我尝试用 { 替换它们并用 {} 转义但无济于事.

奇怪的是,如果大括号出现在文本中间(更具体地说,在 Run 元素的 Text 属性中),一切都很好,只有当左花括号位于开头* 结尾花括号* 时,RichTextBox 才会崩溃.我能够通过在每个 Run 的开头和结尾插入带有 ​ 的零宽度空格来解决这个问题.

然而,如果开头有一个左花括号*结尾有一个右花括号*,这个问题就会变得更加复杂.在这种情况下,零宽度空格似乎不再起作用,因此唯一的解决方法是在文本的开头或结尾插入额外的真实"字符,这显然是我做不到的.

这似乎是 RichTextBox 的一个错误,正如 这个答案.显然,它还没有被修复.那么,有人知道我可以尝试的其他解决方法吗?

* 也可以只跟空格或只跟空格

解决方案

好的,经过一番修补后,我找到了一个简单的解决方法.只需输入一个 "zero-width non-joiner" 字符 ‌(‌ 在 XAML 中不起作用)在每个 Run 的开头和结尾.

显然,这个字符的处理方式与我之前使用的零宽度空格不同,即使您的文本在开头 结尾都有花括号也能正常工作.当然还有更多不可见的字符具有相同的效果(检查维基百科上的这个列表)但是我认为零宽度非连接器的副作用应该最小.

I'm currently working on a Twitter app for Windows Phone, in which – via a custom DependencyProperty – the Xaml property of each RichTextBox is bound to the text of a tweet (which includes programmatically generated Run elements with all the text). This works good enough until there are curly braces { and } in the text. I tried replacing them with { and escaping with {} but to no avail.

The weird thing is, if the curly braces show up in the middle of the text (more specifically, in the Text property of a Run element) everything's fine, it's only when an opening curly brace is at the beginning* or a closing curly brace is at the end* that the RichTextBox crashes. I was able to work around this by inserting zero-width spaces with ​ at the beginning and end of each Run.

However, this issue gets more complicated if there is both an opening curly brace at the beginning* and a closing curly brace at the end*. In that case, the zero-width spaces don't seem to work anymore, so the only workaround would be to insert additional "real" characters at either the beginning or end of the text, which I obviously can't do.

This does seem to be a bug with RichTextBox, as acknowledged in this answer over two years ago. Apparently, it hasn't been fixed yet. So, does anyone know of any further workarounds I could try?

* can also be preceeded only by whitespace or followed only by whitespace

解决方案

Okay after some more tinkering I found an easy fix. Just put a "zero-width non-joiner" character ‌ (‌ doesn't work in XAML) at the beginning and end of each Run.

Apparently this character is treated differently than the zero-width space I used previously and even works if your text has curly braces at both the beginning and the end. There are of course even more invisible characters that have the same effect (check this list on Wikipedia) but the zero-width non-joiner should have the least side-effects I think.

这篇关于手动设置 Xaml 属性时在 RichTextBox 中显示花括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆