RSS

Tag Archives: WP8

StringFormat missing for Bindings in Windows Phone 8.1

There is currently no possibility to use StringFormat in bindings if you develop a Windows Phone 8 project. With normal Windows applications this is done with the following XAML code.

<TextBox Text="{Binding Path=MyProperty, StringFormat='{}{0:N0} pcs.'}" />

You will miss this feature in Windows Phone projects. But there is a simple solution to overcome this problem. The solution is to use a class that inherits from IValueConverter. There you provide the logic to apply the formatting of the string.

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

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}

In your XAML you can use this converter as follows:

<Grid>
    <Grid.Resources>
        <converters:StringFormatConverter x:Key="StringFormatConverter" />
    </Grid.Resources>
    <TextBox Text="{Binding Path=MyPropterty,
                            Converter={StaticResource StringFormatConverter},
                            ConverterParameter='{}{0:N0} pcs.'}" />
</Grid>
Advertisements
 
Leave a comment

Posted by on January 14, 2015 in C-Sharp, WP8.1, WPF

 

Tags: ,