0

我有一个 WPF DataGrid(.NET 框架 4),它从 myObject 的数组中获取它的 ItemsSource。myObject 的列/变量之一是 DateTime。有没有办法更改 DataGrid 行的绘图事件,以便我可以在该列的单元格中显示除每个对象的 DateTime 之外的其他内容?

4

1 回答 1

0

设置AutoGenerateColumns为 False,并使用DataGridTextColumnDataGridTemplateColumn 等手动定义列。


使用事件进行编辑AutoGeneratingColumn,您可以通过添加以下内容来修改列的输出IValueConverter

    void MyGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
    {
        // check if the current column is the target
        if (e.PropertyName == "MyDateproperty")
        {
            // assuming it's a Text-type column
            var column = (e.Column as DataGridTextColumn);
            if (column != null)
            {
                var binding = column.Binding as Binding;
                if (binding != null)
                {
                    // add a converter to the binding
                    binding.Converter = new StringFormatConverter();
                }
            }
        }
    }

现在,StringFormatConverter以通常的方式定义,将日期/时间值转换为:

public class StringFormatConverter: IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var col = (DateTime?)value;
        return (col == null) ? null : col.Value.ToShortDateString();
    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
于 2012-09-18T22:28:59.150 回答