我可以动态地将TextBlock.Text的一部分制作成不同的颜色吗?

Bop*_*Bop 4 c# wpf

我的主窗体中有TextBlock.我在应用程序运行期间将Text属性设置为不同的字符串.

我希望能够为特定字符串的部分着色.

伪代码:

if(a < 0) txbStatus.Text = string.Format("{0} <RED>{1}</RED>",  a, b);
     else txbStatus.Text = string.Format("{0} <BLUE>{1}</RED>", a, b);
Run Code Online (Sandbox Code Playgroud)

Joh*_*nny 11

您可以按照您想要的方式拆分字符串,然后使用foreach()循环进行拆分字符串尝试

TextBlockName.Inlines.Add(new Run("colored text") {Foreground = Brushes.Blue});
Run Code Online (Sandbox Code Playgroud)


svi*_*ick 6

a的内容TextBox不一定只是一个字符串,而是一个Inlines 的集合:

txbStatus.Inlines.Clear();
txbStatus.Inlines.Add(new Run("normal color, "));
txbStatus.Inlines.Add(new Run("colored text") { Foreground = Brushes.Red });
Run Code Online (Sandbox Code Playgroud)