SezMe
SezMe

Reputation: 527

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.

Upvotes: 0

Views: 147

Answers (2)

BionicCode
BionicCode

Reputation: 29028

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

Upvotes: 0

UserNam3
UserNam3

Reputation: 655

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

Upvotes: 0

Related Questions