Tim Pohlmann
Tim Pohlmann

Reputation: 4440

Treat ListBox as MultiSelector

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?

Upvotes: 1

Views: 97

Answers (1)

Clemens
Clemens

Reputation: 128136

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;
    ...
}

Upvotes: 1

Related Questions