C#WPF Textblock每行不同的字体颜色

时间:2016-03-04 06:54:21

标签: c# wpf wpf-style

我试图让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";
    }

2 个答案:

答案 0 :(得分:7)

您可以使用ListView

以下是如何使用Run

的示例
Run

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

答案 1 :(得分:3)

使用像这样的文本块

class Solution {

      static int[] coinSet = {1,5,10,25};
      static List<List<Integer>> possibleWays = new ArrayList<>();
      static List<Integer> currentWay = new ArrayList<>();

      private static int makeChange(int amount, int startCoin){

        boolean flag = false;
        for(int i =0 ; i < coinSet.length ; i++){
          if(coinSet[i] == startCoin) {
            flag =true;
          }
        }

        if(!flag){
          throw new IllegalArgumentException("startCoin has to be in the specified range");
        }

        int nextCoin = 0;
        switch(startCoin) {
          case 25:
            nextCoin = 10;
            break;

          case 10:
            nextCoin = 5;
            break;

          case 5:
            nextCoin = 1;
            break;

          case 1:
            possibleWays.add(currentWay);
            currentWay = new ArrayList<>();
            return 1;
        }

        int ways = 0;

        for(int count = 0; count * startCoin <= amount; count++){
          ways += makeChange(amount - (count * startCoin),nextCoin);
        }

        return ways;

      }    
      public int calculateNumberOfWays(int amount, int startCoin) throws Exception {
        if (amount == 0) {
          throw new Exception();    }

        return makeChange(amount, startCoin);
      }

      public static void main(String[] args) {

        System.out.println(makeChange(5,25));
        System.out.println(possibleWays);

      }
    }

并设置值

<TextBlock>
      <TextBlock Name="tbSmallPotion" Foreground="Green"/
      <TextBlock Text="tbMediumPotion"Foreground="Blue"/>
 </TextBlock>