问题
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";
}
回答1:
You can make use of Run
.
Here is the sample of how to use the 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.
回答2:
Use textblock like this
<TextBlock>
<TextBlock Name="tbSmallPotion" Foreground="Green"/
<TextBlock Text="tbMediumPotion"Foreground="Blue"/>
</TextBlock>
and set the values
tbSmallPotion.Text = smallPotion.Name + "(" + smallPotion.AffectValue + ")\r\n";
tbMediumPotion.Text = mediumPotion.Name + "(" + mediumPotion.AffectValue + ")\r\n";
来源:https://stackoverflow.com/questions/35789811/c-sharp-wpf-textblock-different-font-color-per-line