c# - 如何在 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.
我怎样才能用粗体制作一个特定的字符串。段落是动态的。
解决方案
幸运的是,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 });
}
推荐阅读
- java - 如何在以下 Spring Boot 项目 twitter4j-spring-boot-sample 中启动测试类 SpringbootTwitter4jDemoApplicationTest?
- c++ - 符号查找错误:未定义符号:__atomic_load
- c# - .Net5:如何从 Program.cs 获取 EnvironmentName
- linux - 在 hvf MacOS 管理程序上使用 qemu 引导 Linux 时出现无效的操作码异常
- c++ - 为什么“gdb”会打印特定类的类方法?
- amazon-athena - 在 Athena/Quicksight 中处理数组的高性能方式
- ibm-cloud - 如何验证 IBM Cloud Function 以使用 IBM Cloud Foundry API
- html - 如何使引导列缩小到其内容的大小
- python-3.x - 从异步循环运行缓慢的后台阻塞任务
- javascript - 多个 v-for 从 Vue.js 中的嵌套 JSON 数组中获取值