Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String interpolation in XAML

I'm thinking about ways of getting advance of C# 6 string interpolation in XAML, such as using them instead of value converters in some simple scenarios like replacing a zero by an empty string when binding to numbers.

From its design discussions:

An interpolated string is a way to construct a value of type String (or IFormattable) by writing the text of the string along with expressions that will fill in "holes" in the string. The compiler constructs a format string and a sequence of fill-in values from the interpolated string.

However, as I suspected, it seems that they can't be used from XAML since it uses a different compiler to generate the BAML and I find no trace of the strings in the generated .g.i.cs files.

  • Are string interpolations not supported in XAML?
  • What workarounds could there be? Maybe using markup extensions to dynamically compile the string interpolations?
like image 671
jnovo Avatar asked May 26 '15 13:05

jnovo


1 Answers

This sounds a lot like the StringFormat attribute introduced in .Net 3.5. As you quote, "writing the text of the string along with expressions that will fill in 'holes' in the string", this can be performed within a XAML binding like this:

<TextBlock Text="{Binding Amount, StringFormat=Total: {0:C}}" />

Since you can use any of the custom string formats, there's a lot of power under the hood here. Or are you asking something else?

like image 149
karfus Avatar answered Sep 21 '22 07:09

karfus