首页 > 解决方案 > 如何在 C# Wpf MVVM 中基于文本块中的特殊字符拆分字符串后使用内联

问题描述

我有一段包含 ':' 和 '\n' 。我想首先在 '\n' 上分隔字符串(一段),然后基于 ':' 然后需要将 \n 和之间的字符串加粗:

例如: **The definite **article** is the word** : It limits the meaning of a noun to one particular thing. For example, your friend might ask, “Are you going to the party this weekend?” \r\n **The definite article** : It tells you that your friend is referring to a specific party that both of you know about.\r\n **The definite article** :It can be used with singular, plural, or uncountable nouns.

我怎样才能用粗体制作一个特定的字符串。段落是动态的。

标签: c#wpfstringsplit

解决方案


幸运的是,aTextBlock支持内联格式。所以我看到两种情况,我的一般方法会假设,在行首和第一个冒号之间的每一行的文本都必须是粗体,除非该行中没有冒号。

它看起来像这样:

var lines = txt.Split('\n');

foreach(var line in lines)
{
    var parts = line.Split(':');
    for(int i = 0; i<parts.Length; i++)
    {
        txBlock1.Inlines.Add(
            new Run($"{parts[i]}{(i<parts.Length - 1 ? ":" : "\n")}")
                { FontWeight = (i==0 && parts.Length>1) ?  FontWeights.Bold : FontWeights.Regular});
    }
}

但是,如果您确实可以期望字符串以这样一种方式格式化,即每一行中恰好有一个冒号,那么您可以将其缩短一点:

var erg = txt.Split(new char[] { '\n', ':'});
for(int i = 0; i<erg.Length;i++)
{
    var isEven = (i & 1) == 0;
    txBlock1.Inlines.Add(
        new Run($"{erg[i]}{(isEven ? ":" : "\n")}")
        { FontWeight = isEven ? FontWeights.Bold : FontWeights.Regular });
}

推荐阅读