Reputation: 302
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!
EDIT:
The code that was given in the chosen answer worked perfectly for my use case.
On the other hand, I completely understand that this is a violation of the MVVM pattern. I'll use the code you provided in code behind of a xaml view.
The reason behind my original question was that I need to implement a ListBox
that has some disabled ListBoxItems
inside. Those items would have to be unselectable.
I tried to use an Attached Property IsSelectable on my ListBoxItems
and it didn't work well. This attached property was greatly inspired by this post. The problem was that when I was directly selecting a disabled item, the attached property worked perfectly. The item couldn't be selected and it wasn't inside the SelectedItems collection. But if I wanted to select all the items by pressing CTRL+A, all the ListBoxItems
were selected even the disabled ones and were found in the SelectedItems collection.
Upvotes: 1
Views: 1575
Reputation: 37066
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.
Upvotes: 5