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

本文关键字:十进制 格式 DataGrid WPF 运行时 | 更新日期: 2023-09-27 17:52:13

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

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

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

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

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

我弄清楚了如何在不使用转换器的情况下替换自动生成的绑定并动态添加格式。此代码设置当前选定单元格

的列格式。
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
binding StringFormat={binding n3}