【问题标题】:Windows Phone 8.1 XAML StringFormatWindows Phone 8.1 XAML 字符串格式
【发布时间】:2014-07-30 09:44:04
【问题描述】:

我正在尝试显示一些文本以及绑定的数据,例如,我有代码:

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

我想在“速记”之前添加一些文本,根据我的阅读,这可以通过使用 StringFormat 作为 Binding 的属性来实现,类似于:

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

但这似乎不起作用,这不再是 8.1 中的处理方式吗?

【问题讨论】:

  • “似乎不起作用”并不能作为诊断依据。
  • 你是不是错过了' in StringFormat='{0} text I want to add' ?
  • 我得到的错误是:“在'Binding'类型中找不到属性'StringFormat'”
  • 您可以使用 edit 将其添加到问题中。

标签: c# xaml windows-phone-8.1


【解决方案1】:

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}'}" />

【讨论】:

    【解决方案2】:

    就像@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>
    

    希望这会有所帮助,干杯。

    【讨论】:

      【解决方案3】:

      我使用了这种方法(由 Microsoft 编写):https://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.data.ivalueconverter

      效果很好!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-05-23
        • 2015-01-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-11
        • 1970-01-01
        相关资源
        最近更新 更多