2016-03-04 168 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

相關問題