不能在XAML绑定的StringFormat中使用撇号

本文关键字:StringFormat XAML 绑定 不能 | 更新日期: 2023-09-27 18:13:04

我正在尝试使用StringFormat插入撇号(撇号?)周围的值绑定到TextBlock:

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

但是,我得到一个编译错误:

MarkupExtension中的

名称和值不能包含引号。MarkupExtension参数' MyValue, StringFormat='值是'{0}"}'是无效的。

我注意到它对引号是有效的:

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

这是StringFormat的一个bug吗?

不能在XAML绑定的StringFormat中使用撇号

我不确定这是否是一个bug,但我测试了这个方法,它可以工作:

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

似乎StringFormat中的单引号必须使用'进行转义,而不是传统的XML样式&apos;

尝试在&apos之前使用':

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

对我来说唯一有效的解决方案是:删除FallbackValue引号(!),然后转义特殊字符。

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

甚至VS2017 XAML智能感知也丢失了!蓝色的是"它",红色的是"不可能",蓝色的是"更奇怪"……

我甚至测试了这个更复杂的情况,并且带空格和不带引号的文本后面的属性被正确解释:

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

(在VS2017, Framework 4.0上测试)

刚刚遇到了UWP为TimeSpan值创建StringFormatConverter ConverterParameter的问题。由于某些疯狂的原因,TimeSpan.ToString(x)自定义格式字符串需要在文字字符周围加上撇号,尽管DateTimeOffset不需要。似乎没有必要自相矛盾。

无论如何……以上都没有成功。有一种方法可以让XAML设计器显示/工作,但是它产生了一个构建错误。

我决定的解决方案是将格式字符串放在最近的封闭元素的字符串资源中。由于我是在使用Border创建的框中显示值,所以我将格式字符串填充到Border元素的资源中。

StringFormatConverter是NuGet上的Microsoft UWP Toolkit中的一个。

<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>