views:

871

answers:

3

I have a value converter that formats numbers (I can't use SP1 yet unfortunately). It works fine until it gets a percentage.

Here's an example:

<TextBlock Text="{Binding Path=PercentageComplete,
                          Converter={StaticResource NumberFormatter},
                          ConverterParameter='0.00 %'}" />

Unfortunately for me when Double.ToString sees a percentage character, it multiplies the number by 100. In my case, the number is already a percentage and no conversion is needed.

In C#, this would be achieved by escaping the % character with a single quote:

(99.99).ToString("0.00 %")  // gives -> "9999 %"
(99.99).ToString("0.00 '%") // gives -> "99.99 %"

Unfortunately, I cannot use a single quote in the ConverterParameter in the above XAML markup extension. Is there a way of escaping it? I have tried doubling the single quotes and using a backslash, but both failed to compile.

+1  A: 

Untested, but have you tried:

<TextBlock Text="{Binding Path=PercentageComplete,
                      Converter={StaticResource NumberFormatter},
                      ConverterParameter=&quot;0.00 '%&quot;}" />
Rowland Shaw
Fantastic. Works like a charm, though I prefer this variant which also works (and I only tried after your suggestion): `ConverterParameter='0.00 "%'`. Many thanks.
Drew Noakes
Also worth pointing out that the variant I mention doesn't cause VS to mark subsequent code in red, even though it compiles just fine.
Drew Noakes
Ironically I had something similar, but thought it'd work better the other way around, so changed it :)
Rowland Shaw
A: 

A workaround it to avoid the markup extension, but this isn't a direct answer to the question.

<TextBlock>
  <TextBlock.Text>
    <Binding Path="PercentageComplete"
             Converter="{StaticResource NumberFormatter}"
             ConverterParameter="0.00 '%" />
  </TextBlock.Text>
</TextBlock>
Drew Noakes
+2  A: 

You can use String.Format instead of Double.ToString

public object Convert( object value, Type targetType, object parameter, System.Globalization.CultureInfo culture ) {
    string format = (string) parameter;

    return String.Format( format, value );
}

And in your binding expression, use the special {} escape sequence:

<TextBlock Text="{Binding PercentageComplete, Converter={StaticResource NumberFormatter}, ConverterParameter='{}{0:0.00} %'}"></TextBlock>
Adam Sills