C#WPF Textblock每行不同的字体颜色

kal*_*npw 2 c# wpf wpf-style

我试图使WPF文本块上的每行文本以不同的颜色显示.我有以下代码,使整个块的字体颜色为紫色,因为这是它设置的最后一种颜色.我怎样才能使每种药水以不同的颜色显示?

    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 Code Online (Sandbox Code Playgroud)

Gop*_*dar 7

你可以利用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);        
...
Run Code Online (Sandbox Code Playgroud)

尚未验证,但我希望它能帮到你.