Programmatically change selected ListBoxItem
-
10-07-2019 - |
Question
Is it possible to change the selected ListBoxItem
from Code-Behind in Windows Presentation Foundation?
It's a quite simple task really, I have a Next
and Previous
button and they represent the next and previous item in the ListBox
. But, myListBox.items
are of course object representations of what I stored in the ListBox
.
So, how would one fetch the ListBoxItem
to set the IsSelected
property?
Solution
Probably the easier thing to do in your case since you are doing Previous and Next is just increment the SelectedIndex:
//Increment
if(myListBox.SelectedIndex < myListBox.Items.Count -1)
myListBox.SelectedIndex++;
//Decrement
if(myListBox.SelectedIndex > 0)
myListBox.SelectedIndex--;
If you really want to get the ListBoxItem that makes up an object you've thrown in your ListBox, you can do:
ListBoxItem item = myListBox.ItemContainerGenerator.ContainerFromItem(objectIWantToSelect);
item.IsSelected = true;
OTHER TIPS
You have various options:
- use the SelectedItem or SelectedIndex property of the ListBox control
- if you have the ListBoxItem and not the parent ListBox, use ItemsControl.ItemsControlFromItemContainer(listboxitem) to retrieve the parent ListBox (and use the previous properties)
- use the ICollectionView interfaces (CollectionViewSource.GetDefaultView) and its methods(MoveCurrentToNext, MoveCurrentToPrevious)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow