ListBox Selected Items Includes All Items

141 Views Asked by At

After a user clicks on any number of items in a CheckedListBox, I want to programmatically remove the checks on those items when the window is closed. With the CheckedListBox named lstChoices, I have:

For I As Integer = 0 To lstChoices.SelectedItems.Count - 1
    Dim lbi As Xceed.Wpf.Toolkit.Primitives.SelectorItem = CType(lstChoices.ItemContainerGenerator.ContainerFromIndex(I), Xceed.Wpf.Toolkit.Primitives.SelectorItem)
    lbi.IsSelected = False
Next

The problem is that the SelectedItems property is NOT the selected items. Oddly, the SelectedItems.Count property is computed correctly but the loop just goes through the first ListBoxItems up to Count whether they are selected or not.

The documentation says the SelectedItems property "Gets the collection of checked items". Either the documentation is wrong or there's a bug in that control. How can I get just the checked items.

2

There are 2 best solutions below

1
BionicCode On BEST ANSWER

You are currently iterating over the Items collection as ContainerFromIndex returns an item based on the Items property and not the SelectedItems property.

You should iterate the SelectedItems and use lstChoices.ItemContainerGenerator.ContainerFromItem instead:

For index As Integer = 0 To lstChoices.SelectedItems - 1
  Dim selectedItem = lstChoices.SelectedItems(index)
  Dim selectedItemContainer = TryCast(lstChoices.ItemContainerGenerator.ContainerFromItem(selectedItem), Selector)
  selectedItemContainer.IsSelected = False
Next
1
UserNam3 On

You have to be careful to make the difference between the elements of SelectedItems and Items.

Try this :

 For I As Integer = 0 To lstchoices.SelectedItems.Count - 1
    lstchoices.SetItemCheckState(lstchoices.Items.IndexOf(lstchoices.SelectedItems(I)), CheckState.Unchecked)
 Next