Selective coloring on dynamic TextBlock content in WPF

风流意气都作罢 提交于 2019-12-08 08:14:48

问题


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 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:


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);
    }
}


来源:https://stackoverflow.com/questions/2719099/selective-coloring-on-dynamic-textblock-content-in-wpf

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