1

For some reason a ListBox is not a MultiSelector. Instead it implements its own SelectedItems property.
I have a DataGrid and a ListBox and I want to treat them both as a MultiSelector, so that I can do something like this:

var selectedItems = dataGridOrListBox.SelectedItems;

Is there a way to do this?
Also is there a good reason for ListBox not being a MultiSelector?

Clemens
  • 123,504
  • 12
  • 155
  • 268
Tim Pohlmann
  • 4,140
  • 3
  • 32
  • 61
  • 1
    "is there a good reason for ListBox not being a MultiSelector". Yes, MultiSelector is there since framework version 3.5, while ListBox is older. – Clemens Aug 10 '15 at 10:08

1 Answers1

1

You could create your own MultiSelector interface and derived ListBox and DataGrid classes that implement it:

public interface IMultiSelector
{
    IList SelectedItems { get; }
}

public class MyListBox : ListBox, IMultiSelector
{
}

public class MyDataGrid : DataGrid, IMultiSelector
{
}

Use them in XAML like this:

<local:MyListBox ... SelectionChanged="OnSelectionChanged"/>
<local:MyDataGrid ... SelectionChanged="OnSelectionChanged"/>

Now you could access the common SelectedItems property (e.g. in a common SelectionChanged handler) like this:

private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
    var multiSelector = (IMultiSelector)sender;
    var selectedItems = multiSelector.SelectedItems;
    ...
}
Clemens
  • 123,504
  • 12
  • 155
  • 268