views:

212

answers:

1

For selective coloring of static content the following suggestion works fine : http://stackoverflow.com/questions/2435880/is-it-possible-to-seletively-color-a-wrapping-textblock-in-silverlight-wpf

However my content will be generated at runtime. For ex. if the Content generated is : "A Quick Brown Fox" Then I need they string "Brown" to be in color Brown and "Fox" to be in color Red

The Keyword-Color list is fixed and available to me at runtime.

I have looked at the Advanced TextFormatting page on MSDN, but it is too complicated for me, also the sample in there does not compile :(

I am looking at creating a custom control which can do this for me. Let me know if anyone has any idea regarding how to go about this.

Thanks in advance.

+1  A: 

The idea is explained in your link: Have a property for the text in the custom control. Then scan the text for the words, and create appropriate Runs. In the end, assign them all to the TextBox inlines collection.

In this example I simply used string.Split(). You might miss words if they are split by other punctuation.

Dictionary<string, Brush> colorDictionary;
string text;  // The value of your control's text property

string[] splitText = text.Split(' ', ',', ';', '-');
foreach (string word in splitText)
{
    if (string.IsNullOrEmpty(word))
    {
        continue;
    }

    Brush runColor;
    bool success = colorDictionary.TryGetValue(word, out runColor);
    if (success)
    {
        Run run = new Run(word);
        run.Background = runColor;
        textbox.Inlines.Add(run);
    }
    else
    {
        Run run = new Run(word);
        texbox.Inlines.Add(run);
    }
}
Daniel Rose
thanks, it worked for me, but I had to create a user control. Isnt subclassing Textblock a better way to do it? but there is nothing to override in TextBlock class
Nitin Chaudhari
With a UserControl you can control what is visible "outside". I don't think there's anything wrong with using UserControls.
Daniel Rose
What i need is a special case of TextBlock (here i think custom control shud be the solution) and not specially controlled TextBlock (that would be user control).
Nitin Chaudhari