简体   繁体   中英

Code equivalent of XAML snippet

I want to know the code equivalent of the part that is inside the TextBlock :

<TextBlock>
     Hello
     <Run Background="Red">S</Run>
     <Run Background="Blue">O</Run>
</TextBlock>

The reason is that I have a converter that returns the TextBox content, but I'm not sure what type to return from the converter. I tried some collection types, that contain the string and the 2 Run instances but that wouldnt work.

Also I noticed that the following wouldnt work:

<TextBlock>
    <TextBlock.Text> <--- Added this
        Hello
        <Run Background="Red">S</Run>
        <Run Background="Blue">O</Run>
    </TextBlock.Text>
</TextBlock>

So my second question is to which property do I have to bind my converter result?

Firstly, you can add Run blocks via the InLines property, eg

TextBlock txtBlock = new TextBlock();

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

Secondly, you cannot add via "TextBlock.Text" as this is expecting a string, not a collection of Runs.

Try this:

    <Label>
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="Hello"/>
            <TextBlock Background="Red" Text="S"/>
            <TextBlock Background="Blue" Text="O"/>
        </StackPanel>
    </Label>

Add your converter to the binding of each textblocks.I think its more flexible than using the Run

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM