15

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?

4
  • "Doesn't seem to work" is not much of diagnostic.
    – ℍ ℍ
    Jun 9, 2014 at 19:16
  • aren't you missing the ' in StringFormat='{0} text I want to add' ? Jun 9, 2014 at 19:22
  • 1
    Error I was getting was: "The property 'StringFormat' was not found in type 'Binding'"
    – blawford
    Jun 9, 2014 at 19:30
  • You can use edit to add that to the question.
    – ℍ ℍ
    Jun 10, 2014 at 8:21

3 Answers 3

30

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

Like @KooKiz pointed out StringFormat at the moment isn't supported, but you could accomplish the same effect just breaking out your lines into inline Runs without a converter like;

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

Hope this helps, cheers.

0

I used this approach (Written by Microsoft): https://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.data.ivalueconverter

It works great!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.