Completely managing a DataGrid from code is not easy.
I tried when I created the DataGridJson custom component, but then I decided to go with a hybrid solution, with two templates.
Try to have a look at this, maybe you will find some of the answers you are looking for: DataGridJson - A DataGrid with quick simple setup