2

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

2 回答 2

9

你可以利用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);        
...

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

于 2016-03-04T07:06:34.833 回答
4

像这样使用文本块

<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";
于 2016-03-04T07:07:55.900 回答