Tips on WPF Autogenerating/ed Datagrid

After making improvements in my WPF datagrids, which I like automatic mode, I added several things like stringformat, keeping sorting, adding columns and else.

First, let’s check the DateTime, by default it is a DatagridTextColumn with an stringformat containing date, hour and PM. In order to change this:

DG1.AutoGeneratingColumn += (s, e) =>
if (e.PropertyType == typeof(DateTime) || e.PropertyType == typeof(Nullable<DateTime>))
(e.Column as DataGridTextColumn).Binding.StringFormat = "dd/MM/yyyy";

Second, let’s remove several properties in my grid, I could add a DescriptionTag over my Fields or Properties (check my other posts) or simply do the following:

DG1.AutoGeneratingColumn += (s, e) =>
   List<String> properties = new List<string>() { "A","B","C"};
   if (properties.Contains(e.PropertyName))
       e.Cancel = true; return;

Third, after the datagrid is created, let’s add another Column with TextBlock in view mode and DatePicker in edit mode:

DG1.AutoGeneratedColumns += (s, e) =>
    DataGridTemplateColumn dgct = new DataGridTemplateColumn();
    dgct.Header = "Limit";
    dgct.SortMemberPath = "Limit";

    Binding b = new Binding("Limit");
    b.StringFormat = "dd/MM/yyyy";

    #region Editing
    FrameworkElementFactory factory = new FrameworkElementFactory(typeof(DatePicker));
    factory.SetValue(DatePicker.SelectedDateProperty, b);
    DataTemplate cellEditingTemplate = new DataTemplate();
    cellEditingTemplate.VisualTree = factory;
    dgct.CellEditingTemplate = cellEditingTemplate;

    #region View
    FrameworkElementFactory sfactory = new FrameworkElementFactory(typeof(TextBlock));
    sfactory.SetValue(TextBlock.TextProperty, b);
    DataTemplate cellTemplate = new DataTemplate();
    cellTemplate.VisualTree = sfactory;
    dgct.CellTemplate = cellTemplate;

    DG1.Columns.Insert(1, dgct);

And that’s all, we have modified and added columns keeping the auto mode in the datagrid.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s