如何更改文本块中特定单词的前景?

How to change the foreground of a specific word in a textblock?

我有一个文本块,用户可以在其中看到堆栈跟踪,如下所示:

System.ArgOutOfRangeExc.:
Argument is out of range.
Parametername: index
at System.Collections.ArrayList.getItem(Int32 index)
//...
at SomethingElse.formData.formData_CloseForm(Object sender, FormClosingEventArgs e)

想法是,像 "System...." 这样的所有东西都变成灰色,堆栈跟踪的其余部分(这里:"at SomethingElse....")不应该被着色。

我不知道如何开始,从哪里开始以及如何解决这个问题。任何解决方案?我正在使用 C# 和 WPF

编辑:文本框中的文本不是静态的。每次用户单击 DataGrid 中的一行时文本都会更改,因此我需要以编程方式执行此操作(使用 Substring 会变得非常复杂)

您可以在 TextBlock 中简单地使用一些 Run 个元素。每个 Run 都可以有自己的格式。举个简单的例子:

<TextBlock FontSize="14" Margin="20">
    <Run Text="This is Green," Foreground="Green" />
    <Run Text="this is Red" Foreground="Red" />
    <Run Text="and this is Blue AND Bold" Foreground="Blue" FontWeight="Bold" />
</TextBlock>

请注意 Run.Text 属性 是一个 DependencyProperty,因此您也可以数据绑定它的值。这也可以通过编程方式完成:

<TextBlock Name="TextBlock" FontSize="14" Margin="20" />

...

private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
    Run run = new Run("This is Green,");
    run.Foreground = Brushes.Green;
    TextBlock.Inlines.Add(run);
    run = new Run(" this is Red");
    run.Foreground = Brushes.Red;
    TextBlock.Inlines.Add(run);
    run = new Run(" and this is Blue AND Bold");
    run.Foreground = Brushes.Blue;
    run.FontWeight = FontWeights.Bold;
    TextBlock.Inlines.Add(run);
}