如何在C#Wpf MVVM中基于文本块中的特殊字符拆分字符串后使用内联



我有一段包含":"one_answers"\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?” rn **The definite article** : It tells you that your friend is referring to a specific party that both of you know about.rn **The definite article** :It can be used with singular, plural, or uncountable nouns.

我怎么能把一个特定的字符串变成粗体呢?段落是动态的。

幸运的是,TextBlock支持内联格式。因此,我看到了两种情况,我的一般方法会假设,行的开头和第一个冒号之间的每一行的文本都必须是粗体,除非那一行没有冒号。

它看起来是这样的:

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

最新更新