Saturday, June 18, 2011

Binding Command Inside DataGrid Using MVVM

In this post I will show you how to bind the commands inside the data grid control using MVVM pattern. For this post I have continue my last post which is used to explain the data pager using MVVM. For this post I have added DelegateCommand class which is added in the Classes folder. I have only one command in the viewModel (with the name HomeViewModel and is located in the ViewModel folder). The view for the Home is located in the View folder. Here you can see that I have added the HomeViewModel as resource in the home view which you can see in the Image 1.


Image 1
I have mentioned the step in the Image 1 which you can see in Image 1. I have set the name of the resource as homeViewModel in step three I have use same name to set the source of the binding both in the data grid and in the command of the HyperLinkButton. I have used hyper link button which is mostly used in the web. In the command parameter I have passed the CustomerID by using the CustomerID we can find the record from the list.

Image 2
In Image 2 you can see the output of the example code, here I you can see the delete command is added in the first column of the data grid and when you place mouse over the delete it will show the tool tip to show the contact name to delete. Hope you get idea of how to bind the command inside the data grid, by using same technique you can bind the add, edit commands which are commonly use in data grid.You can download the source code from here 

All and any comments / bugs / suggestions are welcomed!

2 comments:

Amrit said...

hi...
when I tried to add the namespace using xmlns:clr-namespace:"MY NAMESPACE" I'am getting a error message "undefined CLR namespace. The clr namespace URI refers to a namespace that is not included in the assembly.

Can you please help me out....

sadanand said...

Dear Asim

I tried your solution and it does work, but then everytime a command fires, and new instance of the ViewModel gets created. This leads me to probably that this may not be the best solution.

Please do post your views on this

Regards
Sadanand Sudeer