代码等效于XAML代码段

thu*_*eys 2 c# wpf xaml

我想知道代码中的部分代码TextBlock:

<TextBlock>
     Hello
     <Run Background="Red">S</Run>
     <Run Background="Blue">O</Run>
</TextBlock>
Run Code Online (Sandbox Code Playgroud)

原因是我有一个返回TextBox内容的转换器,但我不确定从转换器返回什么类型.我尝试了一些集合类型,包含字符串和2个Run实例但不起作用.

另外我注意到以下不起作用:

<TextBlock>
    <TextBlock.Text> <--- Added this
        Hello
        <Run Background="Red">S</Run>
        <Run Background="Blue">O</Run>
    </TextBlock.Text>
</TextBlock>
Run Code Online (Sandbox Code Playgroud)

所以我的第二个问题是我必须绑定转换器结果的属性?

Tim*_*oyd 6

首先,您可以通过InLines属性添加Run块,例如

TextBlock txtBlock = new TextBlock();

txtBlock.Inlines.Add(new Run { Text = "S", Background = Brushes.Red });
txtBlock.Inlines.Add(new Run { Text = "O", Background = Brushes.Blue });
Run Code Online (Sandbox Code Playgroud)

其次,你不能通过"TextBlock.Text"添加,因为这需要一个字符串,而不是一个运行集合.