在运行时更改WPF DataGrid中的十进制格式

时间:2016-06-27 15:19:20

标签: c# wpf datagrid string-formatting

我使用WPF DataGrid来显示SQL Server视图中的数据。我只提供ItemSource自动生成列并显示数据。

对于数字列,我需要用户能够更改显示的小数位数。

经过深入搜索,我发现唯一的解决方案是在StringFormat事件处理程序中设置AutoGeneratingColumn

但我需要在运行时更改StringFormat。你能帮帮我吗?

2 个答案:

答案 0 :(得分:1)

我想出了如何替换自动生成的绑定并在不使用转换器的情况下即时添加格式。此代码集当前所选单元格的列格式

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

答案 1 :(得分:0)

binding StringFormat={binding n3}