Windows Phone 8.1 XAML StringFormat

15

我希望能够显示一些文本以及绑定的数据,例如,我有以下代码:

<TextBlock Text="{Binding Shorthand}"  Style="{ThemeResource ListViewItemTextBlockStyle}" />

我想在“速记”之前添加一些文本,根据我的阅读,可以通过使用Binding的StringFormat属性来实现,大致如下:

<TextBlock Text="{Binding Path=Shorthand, StringFormat={0} text I want to add}"  Style="{ThemeResource ListViewItemTextBlockStyle}" />

然而,这似乎不起作用了,这种方法在8.1中不再适用吗?


“Doesn't seem to work”不是很有诊断意义。 - H H
你不是忘了在 StringFormat='{0} text I want to add' 中加上单引号 ' 吗? - Karthik Ganesan
1
我遇到的错误是:“在类型'Binding'中找不到属性'StringFormat'”。 - blawford
你可以使用“编辑”将其添加到问题中。 - H H
3个回答

30

StringFormat 在 WinRT 上不受支持。 但是,您可以通过创建自定义转换器轻松替换它:

public class StringFormatConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        return string.Format(parameter as string, value);
    }  

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        return null;
    }
}
然后在您的页面资源中声明它:
<Page.Resources>
    <local:StringFormatConverter x:Name="StringFormat"/>
</Page.Resources>

并将它用于您的绑定:

<TextBlock Text="{Binding Path=SomeText, Converter={StaticResource ResourceKey=StringFormat}, ConverterParameter='Hello {0}'}" />

16

正如@KooKiz所指出的那样,目前不支持使用StringFormat,但是您可以通过将行分解为内联运行而不需要转换器来实现相同的效果,例如:

<TextBlock>
   <Run Text="Hey I wanted to put this text in front of "/>
   <Run Text="{Binding Path=Shorthand}"/>
   <Run Text=" and I also wanted some text after it. Neato.."/>
</TextBlock>

希望这会有所帮助,加油!

0

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