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

C# WPF Textblock different font color per line

我正在尝试使 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

下面是如何使用 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);        
...

尚未验证,希望对您有所帮助。

像这样使用文本块

<TextBlock>
      <TextBlock Name="tbSmallPotion" Foreground="Green"/
      <TextBlock Text="tbMediumPotion"Foreground="Blue"/>
 </TextBlock>

并设置值

tbSmallPotion.Text = smallPotion.Name + "(" + smallPotion.AffectValue + ")\r\n";
tbMediumPotion.Text = mediumPotion.Name + "(" + mediumPotion.AffectValue + ")\r\n";