m.lachance m.lachance - 1 year ago 434
C# Question

WPF ListBox.SelectedItems as ListBoxItem

Is there a way to have the selected items of a

as a
in the event
(on the
) in WPF?

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

For example, when I create my
I bind it to a
as a data source, so when I called
I get a list of


Answer Source

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 = 
    .Select(item => (ListBoxItem)listBox.ItemContainerGenerator.ContainerFromItem(item))

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download