Wpf: SelectedItems property on DataGrid

Created on 14 Jun 2020  路  2Comments  路  Source: dotnet/wpf

The DataGrid has a property SelectedItems property which can not be used in WPF like 'SelectedItem' because it has no dependency property. I would love to see this be added to WPF.

See as well: https://stackoverflow.com/questions/9880589/bind-to-selecteditems-from-datagrid-or-listbox-in-mvvm
Here the DataGrid is used with SelectionMode "Extended" and using SelectionUnit="FullRow" --> with this configuration I think there should be no issue adding this functionality.

Here a raw template for a simple extension (only supporting to read the 'SelectedItems' property):

``` c#
public class CustomDataGrid : DataGrid
{
public static readonly DependencyProperty SelectedItemsProperty = DependencyProperty.Register(nameof(SelectedItems), typeof(IList), typeof(CustomDataGrid), new PropertyMetadata(default(IList), OnSelectedItemsPropertyChanged));

    protected override void OnSelectionChanged(SelectionChangedEventArgs e)
    {
        base.OnSelectionChanged(e);
        SetValue(SelectedItemsProperty, base.SelectedItems);
    }

    public new IList SelectedItems
    {
        get => (IList)GetValue(SelectedItemsProperty);
        set => throw new Exception("This property is read-only. To bind to it you must use 'Mode=OneWayToSource'.");
    }

    private static void OnSelectedItemsPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        ((CustomDataGrid)d).OnSelectedItemsChanged((IList)e.OldValue, (IList)e.NewValue);
    }

    protected virtual void OnSelectedItemsChanged(IList oldSelectedItems, IList newSelectedItems)
    {
    }

}
```

issue-type-enhancement

All 2 comments

It would be realy great if you could implement the SelectedItems inside the DataGird/Listbox.
Right now there is, as far as I know, just one solution, that works with virtualisation and a two way binding.
See https://github.com/samueldjack/SelectedItemsBindingDemo
This is the accepted solution from the https://stackoverflow.com/questions/9880589/bind-to-selecteditems-from-datagrid-or-listbox-in-mvvm , that already has been metioned by ice1e0

Was this page helpful?
0 / 5 - 0 ratings