【问题标题】:Can't use apostrophe in StringFormat of a XAML binding?不能在 XAML 绑定的 StringFormat 中使用撇号?
【发布时间】:2011-10-31 05:45:20
【问题描述】:

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

<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 的错误吗?

【问题讨论】:

    标签: c# wpf escaping apostrophe string-formatting


    【解决方案1】:

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

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

    甚至 VS2017 XAML Intellisense 也丢失了!它以蓝色显示“It”,以红色显示“couldn”,以蓝色显示“be more怪异”……但它确实有效。

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

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

    (在 VS2017 上测试,框架 4.0)

    【讨论】:

    • 在 VS 16.4.5 (2019) 中仍然表现得像这样
    • 在 VS2022(版本 17.0.4)中为我工作
    【解决方案2】:

    我不确定这是否是一个错误,但我测试了这个方法,它确实有效:

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

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

    【讨论】:

      【解决方案3】:

      尝试在&amp;apos之前使用\:

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

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          猜你喜欢
          • 2014-12-27
          • 2011-03-28
          • 2013-12-10
          • 2012-06-16
          • 1970-01-01
          • 2013-03-12
          • 1970-01-01
          • 2010-12-15
          • 2013-10-17
          相关资源
          最近更新 更多