Skip navigation

Today I got my first WPF working by using a simple Datagrid control. Although the WPF form Datagrid is binded directly to the collectionviewsource, instead of using more sophisticated pattern like adding a data access layer or viewmodel.

First I need to get my context right. It took me some time to get my context working, as I forgot to instantiate the context. I just declare it but it will only work after I use the new keyword to instantiate. The context needs to be in the form class, in order to be used by all the objects within the form class.

Secondly I need to create the object data source in the project by clicking Data > Add New Data Source, select the project namespace, and add the object I need for the grid. In the Data Source window you can select what default control to present this data source (a Datagrid for this case). Then I just drag the Data Source to the XAML surface and it will create the grid for me.

There are some code auto generated by this drag and drop action. In Window_Loaded event, code is auto generated for me and comments are inserted to remind me to  use the ViewSource.Source method to load data. By using the ToList method I created a list and assign it to the ViewSource.

Finally I need let user update the form. By using the Datagrid.SelectedItem property I could instantiate an object for the row user selected in the grid. Using the AddObject method I could easily add the current selected object/row to the context, then quickly do a SaveChanges.

That’it for my first working WPF form with a Datagrid control. Nothing fancy here, but glad I get it working. Next task for me will be to create a proper MVVM project for a single Entity Type. Let’s see how it goes. Cheers!

Leave a comment