Monday, September 27, 2010

Building Silverlight Application using MVVM Part 2 - Add Item

This is part two of Silverlight Application using MVVM-CRUD Operation  that showcases the basic building blocks of a data centric application. 
In classical applications, the DataGrid or similar UI control takes over the control of data and servers as both the visualizer and data container. When writing logic in such applications, developer deals with DataGrid directly. However with XAML (Silverlight/WPF) there is more stricter separation of duties, UI provides data visualization and all manipulation is done to the data itself.
In order to add new item (row to DataGrid), you have to first add new item to underlying data source, People. When a new Person is added to Person collection (People), a new row appears in the DataGrid. Behind the scenes, when you add new item to the People, the observable collection fires collection changed event that triggers DataGrid to update the UI.
Add a new button, Textblocks and Textboxes to capture the new data to be added to UI as shown below -


Add a method to the PeopleViewModel.cs class in ViewModel folder as shown below -







Add the code for click event of the add button and save button. The code for main page looks like as shown below (You will also need to add
using SilverlightCRUDDemo.Model and using SilverlightCRUDDemo.ViewModel
namespace directives)






















F5 and run the application. Now when you click Add button, a new panel is shown to the right of DataGrid as shown below -

Enter "Jonty" as first name, "Leahy" as last name, 35 as age and "Springfield" as city and click on save button. A new item with the detail specified is added to the datagrid as shown below -





We have done the add item code using button handler as of now. We will revisit Add item feature and enhance it to provide this behavior when we implement ICommand interface in future.

Please note that I have not implemented any validation in this code. I have left the code for updating an item to the user. In my next post, we will be going to learn how to delete an item.

No comments:

Post a Comment