对于静态内容的选择性着色,以下建议效果很好:是否可以在Silverlight/wpf中旋转包装文本块

但是,我的内容将在运行时生成。对于前。如果生成的内容是:“快速棕狐”,那么我需要它们弦“棕色”才能形成棕色,“狐狸”为红色

关键字彩色列表已修复,在运行时我可以使用。

我已经查看了MSDN上的高级文本形式页面,但是对我来说太复杂了,那里的样本也没有编译:(

我正在考虑创建一个可以为我做到这一点的自定义控件。让我知道是否有人知道如何解决这个问题。

提前致谢。

有帮助吗?

解决方案

在您的链接中解释了这个想法:在自定义控件中拥有文本属性。然后扫描文本以获取单词,并创建适当的运行。最后,将它们全部分配给文本框Inline Collection。

在此示例中,我只需使用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);
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top