Reputation: 7553
I am trying to format my string
to have commas every 3 places, and a decimal if it is not a whole number. I have checked roughly 20 examples, and this is the closest I have come:
<TextBlock x:Name="countTextBlock" Text="{Binding Count, StringFormat={0:n}}" />
But I get a The property 'StringFormat' was not found in type 'Binding'.
error.
Any ideas what is wrong here? Windows Phone 8.1 appears to differ from WPF, because all of the WPF resources say that this is how it is done.
(The string
is updated constantly, so I need the code to be in the XAML
. I also need it to remain binded. Unless of course I cannot have my cake and eat it too.)
Upvotes: 6
Views: 3564
Reputation: 89285
It seems that, similar to Binding
in WinRT, Binding
in Windows Phone Universal Apps doesn't have StringFormat
property. One possible way to work around this limitation is using Converter
as explained in this blog post,
To summarize the post, you can create an IValueConverter
implmentation that accept string format as parameter :
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();
}
}
Create a resource of above converter in your XAML, then you can use it like this for example :
<TextBlock x:Name="countTextBlock"
Text="{Binding Count,
Converter={StaticResource StringFormatConverter},
ConverterParameter='{}{0:n}'}" />
Upvotes: 10