Can't use an apostrophe in a StringFormat XAML binding?

I am trying to use StringFormat to insert an apostrophe (apostrophe?) Around a value associated with a TextBlock:

<TextBlock Text="{Binding MyValue, StringFormat='The value is &apos;{0}&apos;'}"/> 

However, I get a compilation error:

Names and values โ€‹โ€‹in MarkupExtension cannot contain quotation marks. Arguments MarkupExtension 'MyValue, StringFormat =' Value '{0}' '}' is not valid.

I notice that it works for quotes:

 <TextBlock Text="{Binding MyValue, StringFormat='The value is &quot;{0}&quot;'}"/> 

Is this a bug with StringFormat?

+12
c # escaping wpf apostrophe string-formatting
source share
4 answers

I'm not sure if this is a bug, but I tested this method and it works:

 <TextBlock Text="{Binding MyValue, StringFormat='The value is \'{0}\''}" /> 

It seems that single quotes inside StringFormat should be escaped with \ , unlike the traditional XML style &apos;

+17
source share

Try using \ before &apos :

 <TextBlock Text="{Binding MyValue, StringFormat='The value is \&apos;{0}\&apos;'}"/> 
+10
source share

This only solution worked for me: remove the FallbackValue quotes (!), And then escape the special character.

 <TextBlock Text="{Binding StateCaption, FallbackValue=It couldn\'t be more weird}" /> 

Even VS2017 XAML Intellisense is lost! it displays โ€œItโ€ in blue, โ€œcannotโ€ red and โ€œbe weirderโ€ blue ... but it works.

I even tested this more complex case, and the attributes following the text with spaces and without quotes are correctly interpreted:

 <TextBlock Text="{Binding StateCaption, StringFormat=It couldn\'t be more weird,FallbackValue=test}" /> 

(tested on VS2017, Framework 4.0)

0
source share

Just ran into this problem for UWP while creating StringFormatConverter ConverterParameter for TimeSpan value. The custom format string TimeSpan.ToString (x), for some crazy reason, requires apostrophes around alphabetic characters, although DateTimeOffset does not. Seems overly controversial.

In any case ... None of the above worked successfully. One approach worked to get the XAML designer to display / work, but he created a build error.

The solution I settled on was to put the format string in the string resource of the nearest enclosing element. Since I displayed the value in a field created using Border, I inserted a format string into the resources of the Border element.

StringFormatConverter is a Microsoft UWP toolkit on NuGet.

 <StackPanel Orientation="Horizontal"> <TextBlock Text="Timespan=" /> <Border BorderBrush="Black" BorderThickness="0.5" Padding="2"> <Border.Resources> <x:String x:Key="TimespanValueConverterParameter">{0:hh':'mm':'ss'.'fff}</x:String> </Border.Resources> <TextBlock Text="{Binding TimespanValue, Mode=OneWay, Converter={StaticResource StringFormatConverter}, ConverterParameter={StaticResource TimespanValueConverterParameter}}" /> </Border> </StackPanel> 
0
source share

All Articles