In an usual application sometimes you need to “adapt” the values from the view model. This is normally done using StringFormat, but we’ll see some other options as well.
Simple StringFormat with binding escape
Let’s say that you need to display a temperature in degrees. In the view model you have just the numerical value and in the interface you want to append the °C string to make it clear what type of degrees are displayed. Here’s how that’s done:
MultiBinding
The zero from XAML binding is actually the first binding. In the next example Name is the {0} part and ID is the {1} part:
There are however some other ways you can concatenate string values in XAML. Let’s review them quickly:
TextBlock with Run text
Using StackPanel to group
Using Converters
TextBlock with Run text
TextBlock supports an inner element called Run which can be helpful when you want to concatenate more things.
Using StackPanel to group
In this case you can just dump everything in a StackPanel having the Orientation set to Horizontal.
Using Converter
And the last example, although I wouldn’t really use it in this case (but shown nonetheless just for completeness sake):
And here’s how to use it in XAML:
Most common formatting specifiers
Formatting numbers using 2 decimal points is done using F2 - F means floating point and the following digit is the number of decimal digits. In this case I used 2, but it can be any value. If you want to show only the integral part then use F0.
If you also want to display the thousands separator you can use N2.
Here are some more examples showing how to display currency and dates: