1

是否可以在 Windows Presentation Foundation 中更改ListBoxItem从 Code-Behind 中选择的内容?

这真的是一个非常简单的任务,我有一个NextPrevious按钮,它们代表ListBox. 但是,myListBox.items当然是我存储在ListBox.

那么,如何获取ListBoxItem设置IsSelected属性?

4

2 回答 2

5

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;
于 2009-10-29T15:52:46.957 回答
1

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)
于 2009-10-29T15:51:56.933 回答