sushmitgos
sushmitgos

Reputation: 153

How to get selected items in wpf datagrid using MVVM

I want to get some selected rows items & try to manipulate them. Currently SelectedItem is giving me only one row at a time. And SelectedItems is not a dependency property. I found a solution by creating our own dependency property to get selected items. Is there any option apart from this?

Upvotes: 2

Views: 6849

Answers (1)

emybob
emybob

Reputation: 1333

Another possible solution is to add an IsSelected property onto the items your showing in your grid

public bool IsSelected
    {
        get { return _isSelected; }
        set
        {
           RaisePropertyChanged(_isSelected, value);
        }
    }

and to then add a style onto the data grid row to change that property.

  <Style TargetType="{x:Type DataGridRow}" >
     <Setter Property="IsSelected" Value="{Binding Path=IsSelected, Mode=TwoWay}" />
  </Style>

Then to get the currently selected items:

  var selectedItems = Items.Where(i => i.IsSelected).ToList();

Upvotes: 11

Related Questions