无法在XAML绑定的StringFormat中使用撇号?

14

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

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

然而,我遇到了编译错误:

在MarkupExtension中,名称和值不能包含引号。 MarkupExtension参数'MyValue,StringFormat =“The value is'{0}'”'无效。

我确实注意到对于引号,它可以正常工作:

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

这是StringFormat的一个错误吗?

4个回答

20

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

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

在StringFormat中似乎必须使用\转义单引号,而不是传统的XML风格&apos;


10
尝试在 &apos 前使用 \
<TextBlock Text="{Binding MyValue, StringFormat='The value is \&apos;{0}\&apos;'}"/>

2
这是我唯一有效的解决方案:移除FallbackValue中的引号(!),然后转义特殊字符。
<TextBlock Text="{Binding StateCaption, FallbackValue=It couldn\'t be more weird}" />

即使是VS2017的XAML智能感知也会出现问题!它会将"it"显示为蓝色、"couldn"显示为红色,而"be more weird"则显示为蓝色...但它还是能够工作。

我甚至测试了这个更复杂的情况,跟在带空格且没有引号的文本后面的属性也能被正确解释:

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

(在VS2017,框架4.0上测试通过)

1
在VS 16.4.5 (2019)中仍然表现如此。 - CAD bloke
1
在我的VS2022(版本17.0.4)中有效。 - kevin.jalais

0

刚遇到为UWP创建StringFormatConverter ConverterParameter的问题,针对TimeSpan值进行转换。 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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接