Change decimal format in WPF DataGrid at runtime

I use the WPF DataGrid to display data from an SQL Server View. I just provide an ItemSource to auto-generate columns and to show data.

For a numeric column, I need the user to be able to change the number of decimal places that are displayed.

After a deep search I've found the only solution is to set the StringFormat in an AutoGeneratingColumn event handler.

But I need to change the StringFormat at runtime. Could you help me with that?

Upvotes: 0

Views: 2128

Answers (2)

Ghotekar Rahul
Ghotekar Rahul

Reputation: 342

binding StringFormat={binding n3}

Upvotes: 0

I figured out how to replace autogenerated bindings and add formatting on the fly without using converters. This code set format of column of currently selected cell

DataGrid dg; // Your DataGrid
var column = (DataGridTextColumn)dg.CurrentCell.Column; // Selected cell's column
var format = column.Binding.StringFormat;
var bind = new Binding(column.Header.ToString()); // Bind to the same column of underlying Source
bind.Mode = BindingMode.OneWay;
bind.StringFormat = "F2"; // Two decimal places, add your code here
column.Binding = bind;// Set new binding

Upvotes: 1

Related Questions