在 WPF ListView 中更改小数分隔符(绑定、字符串格式)

3

我有一个 DataTable,其中包含数字,它是 ListView 的 ItemsSource,并且我希望它们以货币格式显示,使用“,”作为小数分隔符,使用“.”作为千位分隔符。

通常我知道如何在绑定中使用 StringFormat(XAML 和 Code-Behind)来实现这一点,就像这个问题中展示的那样:

更改绑定中的默认千位和小数分隔符

但这次却不起作用:我的 ListView 显示 '.' 作为小数分隔符。我的示例中特殊的是,我需要在运行时生成 GridViewColumns,并在程序中动态加载 DataTemplates,例如:

 GridViewColumn Amount_col= new GridViewColumn();
 Amount_col.Header = "Gesamt";

 DataTemplate dataTemplate = new DataTemplate(typeof(TextBlock));
 FrameworkElementFactory Grid = new FrameworkElementFactory(typeof(Grid));
 FrameworkElementFactory Txtblck= new FrameworkElementFactory(typeof(TextBlock));

 Binding binding = new Binding("AMOUNT");       
 Txtblck.SetBinding(TextBlock.TextProperty, binding);
 binding.StringFormat = String.Format(new CultureInfo("de-DE"), "#,#.00€", Txtblck.Text); //not working
 
 Grid.AppendChild(Txtblck);
 dataTemplate.VisualTree = Grid;
 Amount_col.CellTemplate = dataTemplate;
 Eintraege_view.Columns.Add(Amount_col);

输出结果如下: https://istack.dev59.com/QuN6c.webp (暂不允许包含图片)
但我需要的输出格式是:1.234,67€,而不是1,234.67€。
我还检查了我的CurrentCulture和CurrentUICulture,它们都是“de-DE”。
我还尝试过:
binding.StringFormat = String.Format(new CultureInfo("de-DE"), "{0:N}", Txtblck.Text);

我试图通过NumberFormatInfo来更改小数点和分组分隔符,但这也没有起作用。

我猜问题可能在于Binding、ListView或Textblock,但我无法找到真正的问题。有人能帮助我解决这个问题并让我的分隔符变成逗号吗?

2个回答

2
也许您可以创建一个CultureAwareBinding类,它继承自Binding类:
public class CultureAwareBinding : Binding
{
    public CultureAwareBinding(string path)
        : base(path)
    {
        ConverterCulture = CultureInfo.CurrentCulture;
    }
}

然后,在你的代码中使用这个类:

var binding = new CultureAwareBinding("AMOUNT");       
Txtblck.SetBinding(TextBlock.TextProperty, binding);

我从这篇文章中提取了这段代码。


0

你的 binding.StringFormat 中有错误吧?如果你想要显示 1.234,67€,应该是 #.#,00€ 而不是 #,#.00€

binding.StringFormat = String.Format(new CultureInfo("de-DE"), "#.#,00€", Txtblck.Text);

不幸的是,这也行不通,因为StringFormat总是将“.”作为小数分隔符,输出结果会被CultureInfo更改,所以你不能通过在StringFormat中设置“,”作为小数分隔符来更改它。 - Ambotz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接