I am using two different currencies in my software. Depending on company origin how can I show the currency before numerical data. Either £ or €
<TextBlock Text="{Binding FNetPriceAfterDisc,StringFormat=c}" />
I would like to Bind "c" in code behind. If possible.
I tried this but doesn't work. Not sure what's wrong.
<TextBlock HorizontalAlignment="Center" >
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="Text" Value="{Binding FNetPriceAfterDisc,StringFormat=€0.000}" />
<Style.Triggers>
<DataTrigger Binding="{Binding Country}" Value="UK">
<Setter Property="Text" Value="{Binding FNetPriceAfterDisc,StringFormat=c}" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
I'd give each item a language identifier tag as a string: en-GB
, de
, en-US
, etc. I'd then write a MultiValueConverter and use that to format arbitrary text, with an arbitrary format, for an arbitrary culture. Since the format string to specify "currency" is also a parameter, this can be used for other localization tasks. It's important not simply to hardcode currency symbols: If Italy leaves the Eurozone, you shouldn't have to lose sleep over it (unless the EU pays your salary).
public class CultureFormatConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter,
CultureInfo culture)
{
var value = values[0];
var format = values[1] as String;
var targetCulture = values[2] as string;
return string.Format(new System.Globalization.CultureInfo(targetCulture),
format, value);
}
public object[] ConvertBack(object value, Type[] targetTypes, object
parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Create the converter in Resources somewhere where it'll be in scope:
<local:CultureFormatConverter x:Key="CultureFormatConverter" />
And then use it like so:
<TextBlock>
<TextBlock.Text>
<MultiBinding Converter="{StaticResource CultureFormatConverter}">
<!-- Bind to FNetPriceAfterDisc property of the viewmodel -->
<Binding Path="FNetPriceAfterDisc" />
<!-- To pass a literal value with a binding, assign it to Source -->
<Binding Source="{}{0:c}" />
<!--
Bind to Culture property of the viewmodel: Should be String that returns
"de" for Germany, "en-GB" for UK, null for Pennsylvania and Australia.
If you want a fixed value, make it Source="de" or whatever, not Path="de".
But if you want to use a constant culture value, you might be happier
just using the ConverterCulture parameter to an ordinary binding.
-->
<Binding Path="Culture" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>