C# WPF 文本块每行不同的字体颜色

本文关键字:字体 颜色 WPF 文本 | 更新日期: 2023-09-27 18:37:15

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

C# WPF 文本块每行不同的字体颜色

您可以使用

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";