tags:

views:

65

answers:

2

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 represntations of what i stored in the ListBox.

So, how would one fetch the ListBoxItem to set the IsSelected property?

A: 

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)
Jalfp
Not sure why you got a downvote. Your answer is technically correct. I upvoted to compensate :)
Anderson Imes
Don't know either... Thank you :-)
Jalfp
+2  A: 

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;
Anderson Imes