C# WPF Textblock 每行不同的字体颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35789811/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# WPF Textblock different font color per line
提问by kalenpw
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?
我试图使 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";
}
回答by Gopichandar
You can make use of Run.
您可以利用Run.
Here is the sample of how to use the 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);
...
Haven't verified but I hope it will help you.
还没有验证,但我希望它会帮助你。
回答by Thorarins
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";

