仅将选择的列更改为自定义格式,同时保留所有列在 WPF DataGrid 中保持不变?

Change only choosen columns to a custom format while remaining all columns stay intact in WPF DataGrid?

编辑: 我尝试了 StringFormat,它工作正常但是 DataGrid 只显示了我在 [=12= 中包含的那些列] 实际上只有 VALUEDATE 应该格式化,其余列应该保持完整。意味着现在我必须为每一列手动编写 DataGridTextColumn ? (我有 20 多个专栏,这可能是一项繁琐的工作!)

这里是 C# 的新手。我有一个 DataGrid,它从 DataTable 中获取它的值。我使用 ExcelDataReader 从 Excel 导入 DataSet 并最终将其转换为 DataTable。

• 如何将列 DATE 的格式更改为系统默认格式? (不同系统会有不同的日期格式)
• 如何将列 VALUE 的格式更改为精确的小数点后两位?

在 VB.NET 中,很简单:DataGridView1.Columns(6).DefaultCellStyle.Format = "N2"

我似乎无法在这里完成这项工作。请建议我将这些特定列更改为所提到的格式的最佳方法。 (没有性能下降,看到一些涉及循环和转换器的帖子)

就像VB一样。你可以找到 all numeric string formats here (MSDN)

<DataGridTextColumn Binding="{Binding Path=VALUE, StringFormat=N2}" Header="Value" />

可以设置当前文化

CultureInfo.DefaultThreadCurrentCulture = newCulture;
CultureInfo.DefaultThreadCurrentUICulture = newCulture;
Thread.CurrentThread.CurrentCulture = newCulture;
Thread.CurrentThread.CurrentUICulture = newCulture;

您可能还会发现 this post 有用

您还可以使用 转换器 进行更高级的修改。

您可以处理 AutoGeneratingColumn 事件:

private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    switch (e.PropertyName)
    {
        case "VALUE":
            e.Column = new DataGridTextColumn
            {
                Header = e.PropertyName,
                Binding = new Binding(e.PropertyName)
                {
                    StringFormat = "N2"
                }
            };
            break;
        case "DATE":
            e.Column = new DataGridTextColumn
            {
                Header = e.PropertyName,
                Binding = new Binding(e.PropertyName)
                {
                    StringFormat = Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern
                }
            };
            break;
    }
}