A StackPanel with a horizontal orientation can
concatenate text. This
is demonstrated in the TextConcatenation
project:
Example 1. Silverlight
Project: TextConcatenation File: MainPage.xaml (excerpt)
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center" Background="{StaticResource PhoneAccentBrush}"> <TextBlock Text="Two " /> <TextBlock Text="plus " /> <TextBlock Text="two " /> <TextBlock Text="equals " /> <TextBlock Text="four!" /> </StackPanel> </Grid>
|
Here it is:
It might seem rather silly to
concatenate text in this way, but it’s actually a very useful technique.
Sometimes a program has some fixed text defined in XAML, mixed with
some variable text from code or a data binding. The StackPanel does a
nice job of piecing it together without any extraneous spacing. (In some
cases you can alternatively use a TextBlock
with its Inlines property set to
multiple Run objects.)
Suppose you wanted the background color of the concatenated text to extend a
little further beyond the boundaries of the text. You can’t do it with a Margin property on the StackPanel because that’s space outside the
element. StackPanel doesn’t have a Padding property (alas),
so you’d need to set Margin properties
or Padding properties on all the
individual TextBlock elements, and that
doesn’t sound like fun.
An easier solution is to put the StackPanel in a Border
element, and move all the alignment and Background
settings to that Border:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Border Background="{StaticResource PhoneAccentBrush}"
Padding="12"
CornerRadius="24"
HorizontalAlignment="Center"
VerticalAlignment="Center">
<StackPanel Orientation="Horizontal">
<TextBlock Text="Two " />
<TextBlock Text="plus " />
<TextBlock Text="two " />
<TextBlock Text="equals " />
<TextBlock Text="four!" />
</StackPanel>
</Border>
</Grid>
Now you get a nice
comfortable background with rounded corners: