Is there a more reliable way to format this number as a string?
I haven't been able to reproduce your failure to compile the code. The XAML editor does complain, with the blue squiggly line and the complaint about the type not being found. If you don't mind the in-editor warning, I would expect that you should be able to get it to convert okay.
However, as a general replacement for the StringFormat binding property, you might consider a simple converter:
class StringFormatConverter : IValueConverter
{
public string Format { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
dynamic o = value;
return o.ToString(Format);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
It will work with any type that has a ToString(string) method. You can use it like this:
<Window x:Class="TestSO43152859StringFormatNumber.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:l="clr-namespace:TestSO43152859StringFormatNumber"
xmlns:s="clr-namespace:System;assembly=mscorlib"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<s:Double>98123.45</s:Double>
</Window.DataContext>
<Window.Resources>
<l:StringFormatConverter x:Key="iskNumericConverter" Format="#,##0.00 ISK"/>
</Window.Resources>
<Grid>
<TextBlock HorizontalAlignment="Left" VerticalAlignment="Top"
Text="{Binding Converter={StaticResource iskNumericConverter}}"/>
</Grid>
</Window>
StringFormat={}{0:n2} ISK}, it should produce roughly the same format.StringFormatbinding attribute to always be finicky in this way, but it always compiles. If you're getting errors, sounds like you tripped over something new. You could move the formatting to some other place in the code (e.g. a converter that has a property for the format, or a text property in the view model that formats the numeric property of interest, that sort of thing).StringFormat='{}{0:#,##0.00} ISK'}?