How to specify XAML value (e.g. converter parameter) culture

雨燕双飞 提交于 2020-05-13 06:16:06

问题


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?


回答1:


You can use ConverterCulture property of Binding for this purpose :

<Binding Path="IsDimmed" Converter="{StaticResource boolToDoubleConverter}" 
         ConverterParameter="0.8" ConverterCulture="en-GB"/>



回答2:


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"


来源:https://stackoverflow.com/questions/23111704/how-to-specify-xaml-value-e-g-converter-parameter-culture

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!