2016-03-04 1224 views
2

我想使用不同颜色的WPF文本块显示文本的每一行。我有下面的代码,它使整个块的字体颜色为紫色,因为这是它设置的最后一种颜色。我怎样才能让每个药水以不同的颜色显示?C#WPF Textblock每行不同的字体颜色

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"; 
    } 
+0

,您可以利用Run'的'这里 – Gopichandar

+0

看看此http://www.wpf-tutorial。 com/basic-controls/the-textblock-control-inline-formatting/- 特别是名为RUN和SPAN的部分。 –

+0

使用richtextbox并将其设置为只读,或者您必须为每种颜色设置带有一个文本框的文本块 – Thorarins

回答

6

您可以使用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);   
... 

还没有验证,但我希望它会帮助你的样品。

2

使用文本块这样

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

是的,这将工作,我结束了与Gopichandar的解决方案为简单的有一个文本块。 – kalenpw

相关问题