简体   繁体   中英

Programatically change the contents of a WPF Datagrid Cell

I have a WPF DataGrid (.NET framework 4) that gets its ItemsSource from an array of myObject. One of the columns/variables of myObject is a DateTime. Is there a way to change the drawing event of the DataGrid row so that I can display something else in the cells of that column other than each object's DateTime?

Set AutoGenerateColumns to False, and define your columns manually using DataGridTextColumn , DataGridTemplateColumn`, etc.


Edit using the AutoGeneratingColumn event, you can modify the column's output by adding an 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();
                }
            }
        }
    }

Now, define StringFormatConverter in the usual way, converting the Date/Time value to whatever:

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM