Click here to Skip to main content
15,791,892 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
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 >

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?
Pheonyx 3-Jun-13 6:24am    
I'm not sure how you would do this, but you a standard textbox would not work for it.
I would suggest looking at a Rich Text Box as these allows for formatting of sections of text.

You can specify the color of a subset of the text in a <TextBlock> or <RichTextBlock> using the <Run> element:
<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">

You can use data binding to build this dynamically.
Share this answer
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);
    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
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900