有没有可能为Textblock提供wordwrap建议,就像你可以用HTML做的那样,<SHY> (soft hyphen)或者<WBR> (word break)更复杂,更难维护zero-width-space ​
目前,Textblock在看到必要时会破坏单词,最后会出现像word一样的单词
Stackoverflo
w
我想要的是:
Stackover-
流程
或至少:
Stackover
流程
如果有建议的方法来实现所需,请告诉我.
设置TextBlock.IsHypenationEnabled为 true 实际上会做类似的事情,但如果你想使用标签,你可以使用这样的方法:
/// <summary>
/// Adds break to a TextBlock according to a specified tag
/// </summary>
/// <param name="text">The text containing the tags to break up</param>
/// <param name="tb">The TextBlock we are assigning this text to</param>
/// <param name="tag">The tag, eg <br> to use in adding breaks</param>
/// <returns></returns>
public string WordWrap(string text, TextBlock tb, string tag)
{
//get the amount of text that can fit into the textblock
int len = (int)Math.Round((2 * tb.ActualWidth / tb.FontSize));
string original = text.Replace(tag, "");
string ret = "";
while (original.Length > len)
{
//get index where tag occurred
int i = text.IndexOf(tag);
//get index where whitespace occurred
int j = original.IndexOf(" ");
//does tag occur earlier than whitespace, then let's use that index instead!
if (j > i && j < len)
i = j;
//if we usde index of whitespace, there is no need to hyphenate
ret += (i == j) ? original.Substring(0, i) + "\n" : original.Substring(0, i) + "-\n";
//if we used index of whitespace, then let's remove the whitespace
original = (i == j) ? original.Substring(i + 1) : original.Substring(i);
text = text.Substring(i + tag.Length);
}
return ret + original;
}
Run Code Online (Sandbox Code Playgroud)
这样你现在可以说:
textBlock1.Text = WordWrap("StackOver<br>Flow For<br>Ever", textBlock1, "<br>");
Run Code Online (Sandbox Code Playgroud)
这将输出:

但是,仅使用不带标签的 IsHyphenated,它将是:

尽管:
textBlock1.Text = WordWrap("StackOver<br>Flow In<br> U", textBlock1, "<br>");
Run Code Online (Sandbox Code Playgroud)
将输出:

IsHyphenated 没有标签:

编辑: 在减小字体大小时,我发现我发布的第一个代码不喜欢在用户指定的中断出现空格的情况下添加中断。
| 归档时间: |
|
| 查看次数: |
2886 次 |
| 最近记录: |