xaml StringFormat,接受", "作为小数点。

问题描述 投票:0回答:1

我们有一个文本框的代码,看起来像这样。

 <TextBox  Width="120" Grid.Column="2" Text="{Binding xxxxx, StringFormat=\{0:F2\}%}"
                                        VerticalContentAlignment="Center" HorizontalAlignment="Left" >

问题是用户坚持要求必须使用 "," 作为小数点,因为多年来都是这样做的。

现在的格式化只是跳过它,所以如果你输入22,33%,它就变成2233%。

有什么办法可以让StringFormat同时接受以下两种类型的数据?".""," 作为小数点,或者我必须以其他方式格式化它(我是WPF和xaml新手,所以可能错过了一些明显的东西)?

wpf xaml string-formatting
1个回答
1
投票

你可以用一个转换器对数值进行编程解析。

public class FormatConverter : IValueConverter
{
    private static readonly CultureInfo s_cultureInfo = new CultureInfo("de");

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) =>
        ((decimal)value).ToString("F2") + "%";

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        string a = value.ToString();
        decimal d;
        if ((a?.Contains(",") == true && decimal.TryParse(a, NumberStyles.Any, s_cultureInfo, out d))
            || decimal.TryParse(a, NumberStyles.Any, CultureInfo.InvariantCulture, out d))
            return d;

        return Binding.DoNothing;
    }
}

上面的示例实现使用了一个支持 , 当试图转换一个 string 含有逗号至 decimal.

这是你在XAML标记中使用它的方式。

<Window.Resources>
    <local:FormatConverter x:Key="conv" />
</Window.Resources>
...
<TextBox  Width="120" Grid.Column="2"
          Text="{Binding xxxxx, Converter={StaticResource conv}}"  />
© www.soinside.com 2019 - 2024. All rights reserved.