Andrew Stephens
Andrew Stephens

Reputation: 10203

WPF - how to concatenate textblocks?

I'm developing a scientific application and need to render a string like this:-

Result: 350cps/ppb

The numeric part (350) and the measurement unit ("ppb") are both bound properties, while "Result" and "cps" are localized strings. (Also note that the "Result" resource string doesn't include the ":", so I can re-use the word in other places).

I'm using the following XAML to output such a string:-

<TextBlock>
    <TextBlock Text="{x:Static ar:AppResources.Result}" />
    :
    <TextBlock Text="{Binding Measurement}" />
    <TextBlock Text="{x:Static ar:AppResources.Counts_per_second_abbrev}" />
    /
    <TextBlock Text="{Binding UnitOfMeasure.Name}" />
</TextBlock>

But the problem with this approach is that a space is inserted between each element because they are on separate lines, resulting in something like this:

Result : 350 cps / ppb

To get it formatted correctly I can use the following, but it's not very readable (and the ":" and "/" are easy to miss):-

<TextBlock>
    <TextBlock Text="{x:Static ar:AppResources.Result}" />:
    <TextBlock Text="{Binding Measurement}" /><TextBlock Text="{x:Static ar:AppResources.Counts_per_second_abbrev}" />/<TextBlock Text="{Binding UnitOfMeasure.Name}" />
</TextBlock>

I guess I could use a couple of horizontal StackPanels instead, but is there a "proper" way to concatenate text without the whitespace being added?

Upvotes: 1

Views: 1606

Answers (1)

Andrew Stephens
Andrew Stephens

Reputation: 10203

Never mind, I found this (I hadn't twigged that I could use statics in a MultiBinding):-

<TextBlock>
    <TextBlock.Text>
        <MultiBinding StringFormat="{}{0}: {1}{2}/{3}">
            <Binding Source="{x:Static ar:AppResources.Result}" />
            <Binding Path="Measurement" />
            <Binding Source="{x:Static ar:AppResources.Counts_per_second_abbrev}" />
            <Binding Path="UnitOfMeasure.Name" />
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

Upvotes: 2

Related Questions