【问题标题】:xaml StringFormat that accepts "," as a decimal point接受“,”作为小数点的 xml StringFormat
【发布时间】:2020-08-18 17:04:36
【问题描述】:

我们的文本框代码如下所示:

 <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】:

您可以使用转换器以编程方式解析该值:

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}}"  />

【讨论】:

    猜你喜欢
    • 2021-11-13
    • 1970-01-01
    • 1970-01-01
    • 2021-06-16
    • 1970-01-01
    • 2015-10-16
    • 2015-03-19
    • 2014-12-26
    • 1970-01-01
    相关资源
    最近更新 更多