如何在PowerShell中为动态编辑的XAML TextBlock保留换行与字体样式
问题原因
- 样式丢失:你在XAML中为
editedTextBlock配置的字体、字号是绑定在内部的<Run>元素上的,直接修改TextBlock的Text属性会清空所有内部Inline节点(包括你写的两个),直接替换为无格式纯文本,原有样式自然失效。 - 自动换行异常:你赋值的字符串中自带了手动输入的换行符和行首缩进,
TextWrapping属性的作用是仅对超出容器宽度的内容自动换行,不会清除你手动输入的换行,所以会出现不符合预期的换行效果。
解决方案
直接修改TextBlock内部对应
修改后的PowerShell核心代码如下:
$editedBlock = $aboutBox.FindName("editedTextBlock") # 处理文本,清除所有手动换行和行首缩进,仅保留正常空格 $aboutText = @" This text has been edited by the Powershell script. As you can see, the text wrap feature has been broken by this. It wraps, but also includes the carriage return. This makes it useless for the purpose of creating a dynamic about xml that can be edited by the multiple scripts that will use it. It also strips my font size/styles "@ -replace "`r?`n\s*", " " # 直接修改原有带样式的Run的文本,下标1对应你XAML里第二个带Calibri字体的Run节点 $editedBlock.Inlines[1].Text = $aboutText # 后续的TextWrapping设置可以删掉,XAML里的配置会正常生效
如果你不需要保留那个透明的「IND..」前缀,也可以直接清空原有Inline节点,新建带指定样式的Run添加进去,灵活度更高:
$editedBlock = $aboutBox.FindName("editedTextBlock") # 处理文本同上 $aboutText = @" This text has been edited by the Powershell script. As you can see, the text wrap feature has been broken by this. It wraps, but also includes the carriage return. This makes it useless for the purpose of creating a dynamic about xml that can be edited by the multiple scripts that will use it. It also strips my font size/styles "@ -replace "`r?`n\s*", " " # 清空原有内容,新建带样式的Run $editedBlock.Inlines.Clear() $newRun = New-Object System.Windows.Documents.Run $newRun.Text = $aboutText $newRun.FontFamily = "Calibri" $newRun.FontSize = 20 $editedBlock.Inlines.Add($newRun)
内容的提问来源于stack exchange,提问作者AngelOfChaos
相关产品推荐
相关产品推荐

