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

随声附和 提交于 2019-12-04 02:28:26

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

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

Seems like single quotes within StringFormat have to be escaped using \ as opposed to the traditional XML style &apos;

Alex

Try to use \ before &apos:

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

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

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

Even the VS2017 XAML Intellisense is lost ! it displays "It" in blue, "couldn" in red, and "be more weird" in blue... but it works.

I even tested this more complexe case, and attributes following a 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)

Just encountered this problem for UWP creating a StringFormatConverter ConverterParameter for a TimeSpan value. The TimeSpan.ToString(x) custom format string for some crazy reason requires apostrophes around literal characters even though DateTimeOffset doesn't. Seems needlessly inconsistent.

Anyway... None of the above successfully worked. One approach worked as far as getting the XAML designer to display/work, but it created a build error.

The solution I settled upon was to put the format string in a string resource of the nearest enclosing element. Since I was displaying the value in a box created using Border, I stuffed the format string into the resources of the Border element.

The StringFormatConverter is the one from the 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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!