我以单行方式从数据库获取文本。例如“你好,我的名字是开发人员”。我需要将此文本的部分以粗体显示并将其放入 TextBlock 中。
对于我使用的代码:
overview_text.Text = overView;
Run Code Online (Sandbox Code Playgroud)
其中overview_text TextBlock是TextBlock,overView是来自db的字符串。
我可以根据需要更改数据库字符串,但我需要单个字符串,例如我需要的是:
"Hello my <bold> name </bold> is the Developer"
Run Code Online (Sandbox Code Playgroud)
你能帮我解决这个问题吗?
有很多方法可以达到您想要的结果。这种RichTextBox方式远非最佳,可以追溯到 Windows 窗体控件,在 Windows 窗体控件中实现这一点更加困难。一般来说,在 WPF 中为此使用的最佳类是Run类。
使用该类的许多好处Run包括它的Text属性是可绑定的,我们可以在其上应用所有常用的文本操作属性,如下面的示例所示:
<TextBlock FontSize="16" Padding="25">
<Run Text="Here is some " />
<Run Text="BOLD" FontWeight="Bold" />
<Run Text=" and " />
<Run Text="ITALIC" FontStyle="Italic" />
<Run Text=" and " />
<Run Text="COLOURED" Foreground="LightGreen" />
<Run Text=" text in one TextBlock" />
</TextBlock>
Run Code Online (Sandbox Code Playgroud)
