c# - 在 TextBlock 中环绕文本

标签 c# wpf textblock

是否有可能向文本 block 提供自动换行建议 正如你在 HTML 中使用 <SHY> (soft hyphen) 所做的那样或 <WBR> (word break)或者 甚至更复杂,更难维护 zero-width-space &#8203;

此时文本 block 在它认为有必要时中断单词, 以自动换行结束

Stackoverflo
w

我想要的是:

Stackover-
flow

或至少:

Stackover
flow

如果有实现所需的推荐方法,请告诉我。

最佳答案

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

编辑: 在减小字体大小时,我发现我发布的第一段代码更喜欢在用户指定的中断出现空白的地方添加中断。

关于c# - 在 TextBlock 中环绕文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11451312/

相关文章:

c# - PRISM + MEF -- 无法让区域正常工作

c# - 如何通过隐藏编码将文本 block 放入滚动查看器中? (wpf)

c# - Animate 如何改变 wpf 中的 ColumnDefinition 宽度?

c# - 在自定义样式的按钮中获取 ScrollViewer

c# - 如何在不使用鼠标的情况下执行虚拟鼠标单击 C#

c# - C# 和 .NET 中是否存在 Java URIResolver 概念?

TextBlock : nothing happens when I click on it 中的 C# 超链接

c# - 检测 TextBlock 在 StackPanel 中是否可见

c# - 不失真失真参数

c# - 数据库 'master' 中的 CREATE DATABASE 权限被拒绝。存在同名数据库