Bind to selected items in WPF DataGrid

15,072

Solution 1

The first suggestions i made did not work. I leave them just for historical reasons.

I finally think that the problem is that what you want to do is kind of strange - or error prone. You put your bind to SelectedItem (one item) while you want to be able to select multiple.

I would personally put no binding at all in xaml (except the ItemsSource of course) and track selection changes with the selectionChanged event in the back end code. A link with a similar problem supporting this method is found here

Hope you find a better solution

OLD SUGGESTIONS:

this should solve the issue as you seem to be treating it like a single mode selection Datagrid but you do nto explicitely define it as such:

<DataGrid SelectionMode="Single"

If you want the selection mode to be multiple then you should NOT bind to SelectedIndex

I also wonder why you have both SelectedIndex binding and SelectedItem binding. In any case just one should be needed.

Keep just the SelectedItem binding set SelectionMode to Extended and try again

Solution 2

Have you looked at the "SelectedItems"(not SelectedItem) collection?

Share:
15,072
Hodaya Shalom
Author by

Hodaya Shalom

Updated on June 04, 2022

Comments

  • Hodaya Shalom
    Hodaya Shalom almost 2 years

    I want to know who are the selected items in the DataGrid (insert them to the collection in the ViewModel).

    When I bind to the selected item is changed only when I click on the row (1 row), but when I press ctrl + clicking it remains the first item, why is this happening and is it possible to link all selected items?

    Here my DataGrid:

    <DataGrid SelectedIndex="{Binding SelectedXIndex}" DataContext="{Binding XViewModel}" SelectedItem="{Binding CurrentX}" ItemsSource="{Binding ListX, Mode=TwoWay}" AutoGenerateColumns="False" >
        <DataGrid.Columns>
         ...
        </DataGrid.Columns>
    </DataGrid>
    

    In the XViewModel I have:

    SelectedXIndex (int) for the selected index

    CurrentX (object of class x) for the current selection

    ListX - list of class x