1

对于静态内容的选择性着色,以下建议可以正常工作: Is it possible to seletively color a wrapping TextBlock in Silverlight/WPF

但是我的内容将在运行时生成。例如。如果生成的内容是:“A Quick Brown Fox”,那么我需要他们将“Brown”字符串设为棕色,将“Fox”字符串设为红色

关键字颜色列表是固定的,我可以在运行时使用。

我查看了 MSDN 上的 Advanced TextFormatting 页面,但这对我来说太复杂了,那里的示例也无法编译:(

我正在考虑创建一个可以为我执行此操作的自定义控件。让我知道是否有人对如何进行此操作有任何想法。

提前致谢。

4

1 回答 1

3

您的链接中解释了这个想法:在自定义控件中具有文本属性。然后扫描文本中的单词,并创建适当的 Runs。最后,将它们全部分配给 TextBox 内联集合。

在这个例子中,我只是使用了 string.Split()。如果单词被其他标点符号分开,您可能会错过单词。

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);
    }
}
于 2010-04-27T07:09:25.357 回答