m.lachance m.lachance - 1 month ago 18
C# Question

WPF ListBox.SelectedItems as ListBoxItem

Is there a way to have the selected items of a

ListBox
as a
ListBoxItem
in the event
SelectionChanged
(on the
ListBox
) in WPF?

Right now, when I call
listBox.SelectedItems
I get the list of items in the format of my data source.

For example, when I create my
ListBox
I bind it to a
CustomListBoxViewModel
as a data source, so when I called
SelectedItems
I get a list of
CustomListBoxViewModel
objects.

Thanks!

Answer

Whatever reason you're doing this for, it's probably a serious violation of MVVM that you'll bitterly regret for the rest of your life.

But the first step on the road to perdition is always an easy one.

Here's how:

var listBox = (ListBox)sender;
var selectedListBoxItems = 
    listBox.SelectedItems.Cast<Object>()
    .Select(item => (ListBoxItem)listBox.ItemContainerGenerator.ContainerFromItem(item))
    .ToList();

Just don't come crying to me when it all ends in tears.

No but seriously, there's are a few good reasons to do this kind of thing in WPF, but they're far less common than somebody new to WPF would expect. Pretty much any normal case is best handled by having your C# code interacting only with your data items, and do stuff to the ListBoxItems in XAML via styles and templating. Once you get used to that way of thinking, it's very powerful, flexible, productive, and maintainable. Codebehind is what you do for odd cases when all other reasonable avenues fail. Drag and drop, for example.