【问题标题】:Change decimal separator in WPF ListView (Binding, String Format)更改 WPF ListView 中的小数点分隔符(绑定、字符串格式)
【发布时间】:2020-08-10 17:21:48
【问题描述】:

我有一个带有数字的 DataTable,它是 ListView 的 ItemsSource,我希望它们格式化为带有“,”作为十进制分隔符和“。”的货币。作为组分隔符。

我通常知道它如何在绑定(XAML 和代码隐藏)中与 StringFormat 一起使用,如以下问题所示:

Changing the default thousand and decimal separator in a binding

但这一次它不起作用:我的 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://i.stack.imgur.com/QuN6c.png(暂不支持图片)

但我需要这样的输出格式: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 上,但我找不到真正的问题。有人可以帮我解决这个问题并让我的分隔符成为','。

【问题讨论】:

    标签: c# wpf listview decimal string-formatting


    【解决方案1】:

    也许您可以创建一个继承自 Binding 的 CultureAwareBinding 类:

    public class CultureAwareBinding : Binding
    {
        public CultureAwareBinding(string path)
            : base(path)
        {
            ConverterCulture = CultureInfo.CurrentCulture;
        }
    }
    

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

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

    我从this post提取了这段代码。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 不,不幸的是,这也不起作用,因为 StringFormat 总是采用 '.'作为小数分隔符,然后输出由 CultureInfo 更改,因此您无法通过将“,”设置为 StringFormat 中的小数分隔符来更改它。
      猜你喜欢
      • 2013-05-02
      • 2013-01-31
      • 2016-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多