【问题标题】:Can I have multiple colors in a single TextBlock in WPF?我可以在 WPF 中的单个 TextBlock 中使用多种颜色吗?
【发布时间】:2010-04-24 17:28:02
【问题描述】:

我在文本块中有一行文本,内容如下:

“检测到的 [手势] 精度为 [accuracy]”

在 WPF 中,我可以更改文本块中元素的颜色吗?我可以让文本块有多种颜色吗?例如,我希望整个 TextBlock 为黑色,除了我希望为红色的手势名称。

这在 WPF 中可行吗?

【问题讨论】:

    标签: c# wpf textblock


    【解决方案1】:

    看看这是否有帮助:

     <TextBlock>
          Detected
          <TextBlock Text="{Binding Gesture}" Foreground="Red" />
          with an accuracy of
          <TextBlock Text="{Binding Accuracy}" />
     </TextBlock>
    

    【讨论】:

    • 唯一的问题是这 4 个文本区域(DetectedGesturewith an accuracy ofAccuracy)不会在同一行 - 它们将是单行距相反,在不同的线路上。但我喜欢这个概念。
    【解决方案2】:

    我想你的意思是这样的(不是文本块的样式):

    <TextBlock  FontSize="25" >
       <Run Text="Detected [" Foreground="Red"/><Run Text="gesture" Foreground="Gray"/>
       <Run Text="] with an accuracy of [" Foreground="Yellow"/><Run Text="accuracy]" Foreground="Green"/>
    </TextBlock>
    

    注意:Run 标记之间的每个回车(或换行)之间都有空格。

    【讨论】:

      【解决方案3】:

      我知道这篇文章很旧,但你试过吗? 您实际上可以在 TextBlock 中添加多色文本..

      Xaml: <TextBlock x:Name="txt_Txt"/>
      
      
      foreach (var itm5 in "! Hello World !; %Hello World%".Split(';'))
      {
             if (txt_Txt.Inlines.Count() > 0)
                 txt_Txt.Inlines.Add(new Run("\r\n"));
             foreach (var letter in itm5)
             {
                  if (char.IsSymbol(letter))
                     txt_Txt.Inlines.Add(new Run(letter.ToString()) { Foreground = Brushes.Red });
                  else
                      txt_Txt.Inlines.Add(new Run(letter.ToString()) { Foreground = Brushes.Black });
              }
      }
      

      【讨论】:

        【解决方案4】:

        您可以为此使用RichTextBox 并设置IsReadOnly = true

        【讨论】:

          猜你喜欢
          • 2012-01-12
          • 2021-05-18
          • 2011-07-28
          • 2015-02-11
          • 2021-06-14
          • 2013-04-14
          • 2015-02-27
          • 2020-05-09
          • 2015-12-11
          相关资源
          最近更新 更多