How to specify format culture in a XAML converter
Asked Answered
T

2

9

When we use static double values in XAML, how can we specify in which format they are provided?

Example:

<Rectangle>
  <Rectangle.Opacity>
    <Binding Path="IsDimmed" Converter="{StaticResource boolToDoubleConverter}" ConverterParameter="0.8"/>
  </Rectangle.Opacity>
</Rectangle>

with the converter method

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
   return double.Parse((string)parameter, culture);
}

The problem is that on a machine, where decimals are separated by ,, the conversion method fails or returns a wrong value, respectively.

I do not want to set the InvariantCulture in the Parse() method, because the converter might in some place be used to parse user input, which is why the culture parameter should still be applied.

If I specify the value as a resource with <sys:Double x:Key="dimValue">0.8</sys:Double>, the converter parameter becomes a double type but before being parsed is cast to a string.

So I would like to specify somehow, that the value is indicated in en-GB format like ConverterParameter="0.8" ConverterParameterCulture="en-GB"/>.

Is this possible somehow without the need to create a puffy MultiValueConverter?

Tensor answered 16/4, 2014 at 14:1 Comment(0)
S
10

You can use ConverterCulture property of Binding for this purpose :

<Binding Path="IsDimmed" Converter="{StaticResource boolToDoubleConverter}" 
         ConverterParameter="0.8" ConverterCulture="en-GB"/>
Scotland answered 16/4, 2014 at 14:23 Comment(1)
Man I was close with my guess... 8-)Tensor
P
5

Sometimes I use:

<TextBlock Grid.Column="3" Margin="3" Text="{Binding [Value], Mode=OneTime, StringFormat={}{0:N2}, ConverterCulture={x:Static glob:CultureInfo.CurrentCulture}}" HorizontalAlignment="Right" />

Where glob is:

xmlns:glob="clr-namespace:System.Globalization;assembly=mscorlib"
Particolored answered 16/4, 2016 at 8:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.