chobo2
chobo2

Reputation: 85715

Add a DataGrid Row programmatically?

I created a datagrid(drag and drop) in a wpf application. I then went through the properties window to add the columns manually.

I want to now add rows to this datagrid through my code behind. I would have thought you would make a

DataGridRow row = new DataGridRow();

and then through maybe a Items.Add() or something you would add your values(one for each column).

I am not seeing this so I am wondering how do I do this.

I know I should be like databinding and stuff but I new to wpf and I am making a quick and dirty application and I rather just go with a forloop and make the rows manually.

I rather come back and refactor the area if I ever feel the desire too. I really just want what I am making up and running so I can use it asp.

Upvotes: 0

Views: 326

Answers (1)

brunnerh
brunnerh

Reputation: 184296

One row is one object, the values are the properties on said object. You should not create the container (the DataGridRow) yourself, the DataGrid can do that for you. Just add the data object directly to the Items (or a collection set as ItemsSource, it should implement INotifyCollectionChanged (e.g. ObservableCollection<T>)). The columns should bind the properties on the data object, by default they are created automatically from the data.


In response to a comment: Using the DisplayNameAttribute you can get the spaces out of the headers easily but you need to add the attribute to all the offending properties:

[DisplayName("Full Name")]
public string FullName { get; }

Then subscribe to DataGrid.AutoGeneratingColumn (- oh, there's a hacky solution for this problem in the docs -):

private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    var descriptor = (MemberDescriptor)e.PropertyDescriptor;
    //Takes the value from the attribute if exists & non-default-value, else property name.
    e.Column.Header = descriptor.DisplayName;
}

The hard way would be an algorithm which just splits the existing header strings correctly (would need to consider pascal casing, numbers and abbreviations, probably not so easy to get 100% accuracy).

Upvotes: 1

Related Questions