是否有可能提供一个换行建议给TextBlock ,你可以在HTML做<SHY> (soft hyphen)
或<WBR> (word break)
或 更加复杂,少维护zero-width-space ​
包装文字
目前的文本块符话只是因为它认为必要, 结束了自动换行像
Stackoverflo
W¯¯
我要的是:
Stackover-
流
或至少:
Stackover
流
如果有推荐的方法来实现所需,请让我知道。
是否有可能提供一个换行建议给TextBlock ,你可以在HTML做<SHY> (soft hyphen)
或<WBR> (word break)
或 更加复杂,少维护zero-width-space ​
包装文字
目前的文本块符话只是因为它认为必要, 结束了自动换行像
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;
}
这样你现在可以说:
textBlock1.Text = WordWrap("StackOver<br>Flow For<br>Ever", textBlock1, "<br>");
这个将输出:
然而,只用IsHyphenated没有标签,这将是:
虽然:
textBlock1.Text = WordWrap("StackOver<br>Flow In<br> U", textBlock1, "<br>");
将输出:
个而且IsHyphenated无标签:
编辑: 在减少字体大小,我发现第一个代码我张贴不喜欢加入其中的空格发生用户指定的休息休息。
使用TextFormatter
连同自定义TextSource
来控制文本如何分解和包装。
您需要从TextSource和您的实现派生类,分析你的内容/串并提供包装规则,例如寻找你的<wbr>标签...当你看到一个标签时,你会返回TextEndOfLine
否则你会返回一个TextCharacters
。
一个例子可能在实施TextSource
帮助是在这里:
对于一个非常先进的例子来看一下 “AvalonEdit” 也使用它:
如果您不需要丰富的格式,您也可以调查GlyphRun
。
这些例子非常好! +1虽然,必须有一个更简单的方法来做到这一点。也许是理解一个软连字符或类似的东西的包装文本框。 – 2012-07-12 21:27:57
您可以使用RichTextBox,然后只提供适当定义的RTF。 – 2012-07-12 21:46:22
看起来像个好主意,必须找到它的工作原理。 – 2012-07-12 21:51:54
谢谢!这看起来完全像我想要的。在接受之前必须先尝试一下。 – 2012-07-13 09:21:06
工作良好,只需做两个小改动:1.将textBlock1替换为参数tb 2. //获取发生标记的索引 int i = text.IndexOf(tag); if(i <0) return ret + text; } – 2012-07-16 14:45:05
谢谢,我实际上认为我已经更新了这个......至于检查标签是否存在,如果您仅将它用于需要标签的文本,则不是必需的,如果您希望所有的TextBlocks都具有此功能,您应该进行自定义控制并覆盖文本更改属性... – 2012-07-16 20:42:22