Tips: Concatenating strings in Silverlight XAML using StringFormat





5.00/5 (4 votes)
Using StringFormat to concatenate strings in Silverlight XAML.
Yesterday, in my post "Tips: Formatting Silverlight TextBlock Control", I showed you how to use various tags like Run
, Span
, Bold
, Italic
, and Underline
to format text in a TextBlock
control present in your XAML code. I also described the use of Run
to bind multiple strings inside a TextBlock
control.
Today, in this small post, I will show you a different method to concatenate multiple text content inside a single control.
Here, we will learn a different way to concatenate multiple strings inside a control. It's not a new feature but many beginners don't know about it and hence I thought to share it here so that you will not miss it the next time you have to use it. If you didn't read my previous post on the same topic, please go and read it here: "Tips: Formatting the Silverlight TextBlock Control". This will give you more visibility on it.
In general, this is how we concatenate multiple strings:
<StackPanel Orientation="Horizontal" DataContext="{StaticResource User}">
<TextBlock Text="Welcome "/>
<TextBlock Text="{Binding Name}"/>
<TextBlock Text=" to our site."/>
</StackPanel>
We use multiple TextBlock
s wrapped with a StackPanel
to implement a single line of string. Yesterday we learnt using the <Run>
tag to implement it. Here is the implementation of the same using the <Run>
tag:
<TextBlock DataContext="{StaticResource User}">
<Run Text="Welcome"/>
<Run Text="{Binding Name}"/>
<Run Text="to our site"/>
</TextBlock>
In both cases, we use different tags and thus it creates a number of lines while concatenating. Have you ever wondered if there is an option like in C# to format text? Can we use something like the string.Format()
method to do it in XAML? In this post, we will see how.
Silverlight 4 has a feature called StringFormat
which you can use in your XAML for string concatenation inside a single control. Forget about multiple TextBlock
controls, forget about multiple Run
tags and/or value converters now.
The StringFormat
option allows you to putg all the information in a single element. All you have to do is the following:
<TextBlock DataContext="{StaticResource User}"
Text="{Binding Name, StringFormat='Welcome \{0\} to our site'}" />
That's the code and your concatenated text is ready inside a single control. Use it whenever you want and make your life simpler when displaying multiple text. Remember that it will not help you in multiple binding. If you want to use multiple binding, yesterday's post on <Run>
tag is the way to go.
Please share this with others who you think might need this. Your feedback always counts. Stay tuned for my next post, where I will show you other features of StringFormat
when used inside XAML. Till then, Happy Coding!