简体   繁体   中英

Programmatically change selected ListBoxItem

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?

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;

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM