Home » WPF

WPF MVVM Datagrid Question

Hey all,

I am using VS 2010, the DataGrid ( WPF Toolkit) and MVVM. I am trying create an event handler for the DataGrid. I have bound the DataGrid to an ObservableCollection. Everything works great.

Now I need to hook up my event handlers. I need serveral,  so lets say DoubleClick. I can hook up buttons (  Command="{Binding AddBranchCommand}"  ). This technique doesn't work with the DataGrid.

If I was using the standard code behind, it would be simple. However, since I have a ViewModel class handling my events, I need a way to bind the events to the event handlers in the ViewModel class.

How can I hook up event handlers to the DataGrid?




Ed Horn


2 Answers Found


Answer 1

Hi Ed,

You can check out Marlon Grech's Attached Command Behavior here: http://marlongrech.wordpress.com/2008/12/13/attachedcommandbehavior-v2-aka-acb/. I think MVVM Light Toolkit also implements EventToCommand. I have read it somewhere. Not sure though. Hope this helps.


Answer 2

Hi Ed Horn,

Josh Smith introduces a solution for the command and event in MVVM - RelayCommand, you could refer to the related chapter on the MSDN Magazine: http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

MVVM recommend to handle the VM data, if it needs to handle the UI element, it recommends to use the Tigger to do the simple handler. As we know, VM data drives the UI element, so if you use the RelayCommand, it is better to change the UI by handling the VM data, not changing the UI directly.

Meanwhile, the link Micheal provided is helpful for your scenario.

Hope this helps.


Bob Bao



<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure