C#WPF Textblock每行不同的字体颜色 [英] C# WPF Textblock different font color per line

查看:1031
本文介绍了C#WPF Textblock每行不同的字体颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使WPF文本块上的每一行文本以不同的颜色显示.我有以下代码可使整个块的字体颜色变为紫色,因为这是它设置的最后一种颜色.如何使每种药水显示为不同的颜色?

I am trying to make each line of text on a WPF textblock display in a different color. I have the following code which makes the entire block's font color purple because that's the last color it's set to. How can I make it so each potion is displayed in a different color?

    private void btnShowPotions_Click(object sender, RoutedEventArgs e) {

        tbPotionInfo.Foreground = Brushes.Green;
        tbPotionInfo.Text = smallPotion.Name + "(" + smallPotion.AffectValue + ")\r\n";
        tbPotionInfo.Foreground = Brushes.Blue;
        tbPotionInfo.Text += mediumPotion.Name + "(" + mediumPotion.AffectValue + ")\r\n";
        tbPotionInfo.Foreground = Brushes.Red;
        tbPotionInfo.Text += largePotion.Name + "(" + largePotion.AffectValue + ")\r\n";
        tbPotionInfo.Foreground = Brushes.Purple;
        tbPotionInfo.Text += extremePotion.Name + "(" + extremePotion.AffectValue + ")\r\n";
    }

推荐答案

您可以使用Run.

这是如何使用Run

Run run = new Run(smallPotion.Name + "(" + smallPotion.AffectValue + ")\r\n");
run.Foreground = Brushes.Green;
tbPotionInfo.Inlines.Add(run);   

run = new Run(mediumPotion.Name + "(" + mediumPotion.AffectValue + ")\r\n");
run.Foreground = Brushes.Blue;
tbPotionInfo.Inlines.Add(run);        
...

尚未验证,但希望对您有帮助.

Haven't verified but I hope it will help you.

这篇关于C#WPF Textblock每行不同的字体颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆