Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
316 views
in Technique[技术] by (71.8m points)

c# - Windows Phone 8.1 XAML StringFormat

I am trying to display some text along with binded data, for example, I have the code:

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

I want to add some text before 'Shorthand', from what I have read this would be possible by using StringFormat as a property of the Binding, something along the lines of:

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

However this doesn't seem to work, is this no longer the way to do things in 8.1?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

StringFormat isn't supported on WinRT. However, you can easily replace it by creating a custom converter:

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

Then declare it in your page resources:

<Page.Resources>
    <local:StringFormatConverter x:Name="StringFormat"/>
</Page.Resources>

And use it in your bindings:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...