wpfvb.netcheckedlistboxxceed

ListBox Selected Items Includes All Items


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.


Solution

  • 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