For selective coloring of static content the following suggestion works fine : 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 creati开发者_C百科ng 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.
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);
}
}
精彩评论