WPF textBox中的选择性文本着色 [英] Selective Text Coloring in WPF textBox

查看:321
本文介绍了WPF textBox中的选择性文本着色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在文本框中有选择地为我的文字着色。

我的输入是

Hi, I want to selectively color my text in my text box.
My input is a

List<Tuple<String,int>> MyList



示例:

输入:


Example :
Input :

<"Hi",    1 >
<"my",    1 >
<"name",  1 >
<"is",    1 >
<"Rohith",2 >
<".",     1 >





我希望它显示为(每个字符串用空格分隔):您好我的名字是 Rohith 。其中Rohith为红色,其余为黑色,1代表黑色,2代表我的程序中的红色。我的列表中有更多颜色。



有人能指出我已经完成的一些资源或请以任何可能的方式帮助我吗?



I want it to be displayed as(each string is separated by a space) : Hi my name is Rohith . Where Rohith is in red and the rest are in black as 1 represents black and 2 represents red in my program. There are a lot more colors in my list.

Can anyone point me to some resources where this has been done or please help me out in any way possible?

推荐答案

您可以在< TextBlock>中指定文本子集的颜色。或< RichTextBlock>使用< Run>元素:

You can specify the color of a subset of the text in a <TextBlock> or <RichTextBlock> using the <Run> element:
<TextBlock>
<Run Text="Hi" Foreground="Black">
<Run Text="my" Foreground="Black">
<Run Text="name" Foreground="Black">
<Run Text="is" Foreground="Black">
<Run Text="Rohith" Foreground="Red"><Run Text="." Foreground="Black">
</TextBlock>



您可以使用数据绑定动态构建它。


You can use data binding to build this dynamically.


谢谢Matt T Heffron的解决方案。以下是我在代码背后的做法



Thanks Matt T Heffron for the solution. Here is how I did it on code behind

FlowDocument fldoc = generateFlowDocument(MyList);
richTextBox.Document = fldoc;


private FlowDocument generateFlowDocument(List<Tuple<String,int>> MyList)
{
    FlowDocument fd = new FlowDocument();
    System.Windows.Documents.Paragraph para = new System.Windows.Documents.Paragraph();
    foreach (Tuple<String,int> word in MyList)
    {
        Run run = new Run(word.Item1 + " ");
        run.Foreground = returnBrushColour(word.Item2);
        para.Inlines.Add(run);
    }
    fd.Blocks.Add(para);
    return fd;
}

private Brush returnBrushColour(int colour)
{
    if (colour == 1)
    {
        return Brushes.Black;
    }
    else if (colour == 2)
    {
        return Brushes.Red;
    }
    //this goes on for a while but i guess you should get the idea
}


这篇关于WPF textBox中的选择性文本着色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆