简体   繁体   中英

Detecting if an item is selected or not in a listbox (WPF)

I want to know how you can know if an item selected or not in the items array of a listbox. The listbox allows multiple selections so I need to iterate all of them and see which are selected and which are not.

Many thanks (I know - short and sweet)

Look at the SelectedItems property, and iterate through that to see which items are selected.

If you want to go through all items you can compare the two collections (MyListBox.Items and MyListBox.SelectedItems) and see which ones match.

something like:

foreach(Item item in MyListBox.Items)        
    if(MyListBox.SelectedItems.Contains(item)
        MyObject.Value = true;
    else
        MyObject.Value = false;

Overkill though really! I guess there is a purpose if you want to do something to all items which are not selected though, is that what you are looking to do?

There are much better ways to do this though - Randolpho is correct, databinding would be a better way to go about this depending on how your data is organised/input and how big the listbox is.

ListBox has a SelectedItems property. That collection will have references to the items that have been selected.

I haven't worked on WPF & this is purely based on MSDN.
Look at SelectedItems propeerty.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM