Handling DataGrid.SelectedItems in an MVVM-friendly manner

.NET, Blend, MVVM, Silverlight, Technical stuff, Work, WPF
See comments

An interesting question from one of the MVVM Light users today:

Is there an MVVM-friendly way to get a DataGrid’s SelectedItems into the ViewModel?

The issue there is as old as the DataGrid (that’s not very old but still): SelectedItem (singular) is a DependencyProperty and can be databound to a property in the ViewModel. SelectedItems (plural) is not a DependencyProperty.

Thankfully the answer is very simple: Use EventToCommand to call a Command in the ViewModel, and pass the SelectedItems collection as parameter. For example, if the command in the ViewModel is declared as follows:

public RelayCommand<IList> SelectionChangedCommand
{
    get;
    private set;
}

and (in the MainViewModel constructor):


SelectionChangedCommand = new RelayCommand<IList>(
    items =>
    {
        if (items == null)
        {
            NumberOfItemsSelected = 0;
            return;
        }

        NumberOfItemsSelected = items.Count;
    });

Then the XAML markup becomes:

<sdk:DataGrid x:Name="MyDataGrid"
                ItemsSource="{Binding Items}">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="SelectionChanged">
            <cmd:EventToCommand
                Command="{Binding SelectionChangedCommand}"
                CommandParameter="{Binding SelectedItems,
                    ElementName=MyDataGrid}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</sdk:DataGrid>

I slapped a quick sample and published it here (VS2010, SL4 but the concept works in SL3 and WPF too).

Cheers!

Laurent

Previous entry | Next blog entry

Responses to “Handling DataGrid.SelectedItems in an MVVM-friendly manner”

  1. Consulting Mechanic Says:

    With MVVM Light 5 and the EventToCommand removed, how would you do the same thing?

  2. lbugnion Says:

    EventToCommand is only absent from the Windows Store version of MVVM Light. If you are using this version (Windows 8.1 and up), use InvokeCommandAction instead. If you are using any other version, use EventToCommand just like described in this article.

    Hope it helps,
    Laurent

Comments for Handling DataGrid.SelectedItems in an MVVM-friendly manner