3

I have a DataTable with numbers which is the ItemsSource for a ListView and I want them to format as currency with ',' as decimal seperator and '.' as group separator.

I usually know how it works with StringFormat in a Binding (XAML and Code-Behind), as also shown in this question:

Changing the default thousand and decimal separator in a binding

But it doesn't work this time: my ListView shows '.' as Decimal separator nevertheless. the special thing in my example is that I need to generate the GridViewColumns during Runtime and I load DataTemplates into them programatically, for example:

 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);

The output is following: https://i.stack.imgur.com/QuN6c.png (not allowed to include pictures yet)

But I need a output formatted like this: 1.234,67€ and not 1,234.67€.

I also checked my CurrentCulture and CurrentUICulture which are both "de-DE".

I also tried:

binding.StringFormat = String.Format(new CultureInfo("de-DE"), "{0:N}", Txtblck.Text);

And I tried to change the decimal and group separator through NumberFormatInfo but that didn't work either.

I guess the problem is the Binding, the ListView or the Textblock but I'm not able to find the real problem. Could somebody help me to solve this problem and make my seperator a ','.

Ambotz
  • 121
  • 7

2 Answers2

2

Maybe you can create a CultureAwareBinding class, that inherits from Binding:

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

Then, use this class in your code:

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

I extracted this code from this post.

joaco
  • 36
  • 5
0

Isn't there mistake in your binding.StringFormat? It should be #.#,00€ instead of #,#.00€ if you want 1.234,67€.

binding.StringFormat = String.Format(new CultureInfo("de-DE"), "#.#,00€", Txtblck.Text);
grzegorzorwat
  • 405
  • 1
  • 4
  • 13
  • No unfortunately that doesn#t work either, because StringFormat always takes '.' as the decimal seperator and the output is then changed by CultureInfo so you can't change it by setting ',' as the decimal seperator in StringFormat. – Ambotz Aug 17 '20 at 05:44