Need to format dates in dynamically built WPF DataGrid

后端 未结 8 606
眼角桃花
眼角桃花 2020-12-05 09:51

We are binding an unknown result set to a WPF DataGrid at run time. Some of our columns are going to contain DateTime values and we need to properly format these date time

8条回答
  •  我在风中等你
    2020-12-05 10:23

    I figured out how to do this in code...hopefully there is a way to mimic this in XAML. (Please post if you find a working XAML sample.)

    To accomplish this in code, add an event handler for the Grid's AutoGeneratingColumn event, such as:

    private void ResultsDataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
    {
        if (e.PropertyType == typeof(DateTime))
        {
            DataGridTextColumn dataGridTextColumn = e.Column as DataGridTextColumn;
            if (dataGridTextColumn != null)
            {
                dataGridTextColumn.Binding.StringFormat = "{0:d}";
            }
        }
    }
    

提交回复
热议问题