在TextBlock中包装文本

时间:2012-07-12 11:55:41

标签: c# wpf textblock

是否有可能为Textblock提供wordwrap建议 正如您可以使用<SHY> (soft hyphen)<WBR> (word break)或 更复杂,更难维护zero-width-space &#8203;

目前Textblock在看到必要时会破坏文字, 结束像

这样的词汇
  

Stackoverflo
  瓦特

我想要的是:

  

Stackover-
  流量

或至少:

  

Stackover
  流量

如果有建议的方法来实现所需,请告诉我。

2 个答案:

答案 0 :(得分:4)

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>");

这将输出:

Just tested

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

IsHypehnated Scenario1

虽然:

textBlock1.Text = WordWrap("StackOver<br>Flow In<br> U", textBlock1, "<br>");

将输出:

Doesn't add <brs> here

IsHyphenated没有标签:

IsHyphenated Scenario 2

修改 在减少字体大小时,我发现我发布的第一个代码并不更喜欢在用户指定的中断处添加空格。

答案 1 :(得分:3)

TextFormatter与自定义TextSource结合使用,以控制文本的分解和包装方式。

您需要从TextSource派生一个类,并在您的实现中分析您的内容/字符串并提供您的包装规则,例如寻找你的&lt; wbr&gt;标记...当您看到标记时返回TextEndOfLine,否则返回TextCharacters

有助于实施TextSource的示例如下:

有关非常高级的示例,请查看“AvalonEdit”,它也使用它:

如果您不需要丰富的格式,也可以调查GlyphRun