如何让自动换行将字符串中的空格视为常规字符? [英] How to make wordwrap consider a whitespace in a string as a regular character?

查看:48
本文介绍了如何让自动换行将字符串中的空格视为常规字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个多行文本框控件,当所有字符都是等宽的并且找到合适的字体大小(例如 - 对于具有 6 列的文本框,应准确输入 6 个字符).- 当然是自动换行!

I want to create a multiline textbox control that will be used for an application as "Snap to grid" when all of the characters are Monospaced, and the fitting font size was found (for example - for a textbox with 6 columns, exactly 6 characters should be entered). - Of course with Word Wrap!

至于上述 - 没关系.找到了计算字体大小的正确方法.

As for the above - it's OK. The correct way to calculate the font size was found.

唯一的问题是我需要创建一个Alt+Enter"选项来代表Enter".

The only issue is that I need to create an "Alt+Enter" option to represent "Enter".

出于某些原因,我不能使用 \r\n 并且需要所有剩余的行空间都充满空格.问题是 wrap 不接受大于文本框宽度的空格.例如:

For some reasons, I can't use \r\n and need that all of the remaining line space will be full of whitespaces. The thing is that wrap doesn't accept spaces in an amount which is larger than the textbox's width. For example:

如果我在一个宽度为 8cells 的文本框中输入以下内容(或粘贴该字符串等):

If I write in a textbox with width=8cells, the following (or paste that string etc..):

世界你好!"(Hello+6Whitespaces+World!")

"Hello World!" ("Hello+6Whitespaces+World!")

我想收到:(_=空格)

I would like to recieve: (_=whitespace)

第一行:你好___

第二行:___世界

第三行:!

真正发生的是:

第一行:你好___

第二行:世界!

(第二行开头没有空格)

(No spaces at all in the beginning of the second line)

PS - 在调试时,我可以看到空格(所有空格)被视为字符串的一部分.

PS - On debug I can see that the spaces (all of them) are considered as a part of the string.

推荐答案

首先,尝试 Environment.NewLine 而不是 \r\n.这将确保您在目标平台上获得正确的换行符.

Firstly, try Environment.NewLine instead of \r\n. That will ensure you get the correct line breaks on your target platform.

其次,Word Wrap 可能会忽略多余的空格,因此您需要用 unicode 不间断空格替换普通空格.其 unicode 字符是 \u00A0.

Secondly, Word Wrap is likely ignoring extra spaces, so you need to replace normal spaces with a unicode non-breaking space. The unicode character for that is \u00A0.

您需要用 unicode 不间断空格替换所有普通空格:

You need to replace all normal spaces with the unicode non-breaking space:

string spaceReplacer = "\u00A0";

要使用它,试试这个:

textBox1.Text = textBox1.Text.Replace(" ", spaceReplacer);

甚至这个:

textBox1.Text = textBox1.Text.Replace(" ", "\u00A0");

这篇关于如何让自动换行将字符串中的空格视为常规字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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