Can I have multiple colors in a single TextBlock in WPF?

杀马特。学长 韩版系。学妹 提交于 2019-11-28 03:17:55

问题


I have a line of text in a textblock that reads:

"Detected [gesture] with an accuracy of [accuracy]"

In WPF, is it possible for me to be able to change the color of the elements within a textblock? Can I have a textblock be multiple colors? For example, I would like the whole TextBlock to be black except the gesture name, which I would like to be red.

Is this possible in WPF?


回答1:


See if this helps:

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



回答2:


you can use a RichTextBox for that and set IsReadOnly = true




回答3:


I know this post is old, but have you tried this?? You can actually add multi colored text, this way in a 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 );
        }
}


来源:https://stackoverflow.com/questions/2705444/can-i-have-multiple-colors-in-a-single-textblock-in-wpf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!