Binding a DataGrid_SelectionChanged to ViewModel?

Nov 4, 2009 at 4:55 PM


I think I remember seeing a way to bind an event like SelectionChanged that normally gets handled in the codebehind in a WPF app get sent to the ViewModel instead but I don't seem to be able to find info on it again. It might have been done using AttachedBehaviors but I don't remember for sure, but I think it was pretty simple. Is anyone sending their events to the ViewModel?

Thanks in Advance!


Nov 4, 2009 at 8:03 PM

TwoWay bind the WPF DataGrids CurrentItem dependency property to a property on your view model.  When the user selects a different item in the grid the property will change on your ViewModel.  You can call a method when the property changes or listen for property changes and call a method...

In your ViewModel...

        #region CurrentItem
        private TViewModel _CurrentItem;
        public TViewModel CurrentItem
            get { return _CurrentItem; }
                if (_CurrentItem != value)
                    _CurrentItem = value;
                    if (CurrentItem != null)
        #endregion CurrentItem
In your view bound to the ViewModel
<WpfToolkit:DataGrid  x:Name="MainDataGrid" ItemsSource="{Binding ViewModels}" CurrentItem="{Binding CurrentItem, Mode=TwoWay}" SelectionMode="Single">
    <WpfToolkit:DataGridTextColumn Header="Header" Binding="{Binding Model.Value}" IsReadOnly="True" />
When the user selects a different row the CurrentItem property updates to reflect the selection and you can do something when this happens.
Nov 17, 2009 at 3:58 PM

Thanks Andy! This does work. Now we realize that we need to have MultiSelect on the DataGrid and recognize that in the ViewModel. This seems that it would be something that a lot of people would do.

I'm finding some challenges in using MultiSelect in MVVM and am sure that I'm just missing something simple. I can use the "IsSelected" in the ViewModel to get the event when selecting a row in the DataGrid. This works fine for a single selection. If I set "SelectionMode=Extended" I still only get the event on the selection of the first row in the DataGrid. SelectionChanged in the codebehind gets each selection event but I really want to make this work in the ViewModel. There is probably a simple solution to this multiSelect that I am just missing. I also tried binding SelectedItems (plural) to a collection to get all of these, but SelectedItems is readonly so it can't be bound to. I sure would appreciate any ideas on how to do this as I can't get this method moved from the codebehind to the ViewModel.
I found some MSDN Documentation for the WPF DataGrid in .NET 4.0 but not for 3.5. Has anyone seen any documentation for the toolkit or datagrid for .NET 3.5?