简体   繁体   English

以编程方式更改选定的ListBoxItem

[英]Programmatically change selected ListBoxItem

Is it possible to change the selected ListBoxItem from Code-Behind in Windows Presentation Foundation? 是否可以从Windows Presentation Foundation中的Code-Behind更改选定的ListBoxItem

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 . 实际上,这是一个非常简单的任务,我有一个NextPrevious按钮,它们代表ListBox的下一个和上一个项目。 But, myListBox.items are of course object representations of what I stored in the ListBox . 但是, myListBox.items当然是我存储在ListBox中的对象的对象表示。

So, how would one fetch the ListBoxItem to set the IsSelected property? 因此,如何获取ListBoxItem来设置IsSelected属性?

Probably the easier thing to do in your case since you are doing Previous and Next is just increment the SelectedIndex: 在您的情况下,可能更容易做,因为您正在执行Previous和Next,只需增加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: 如果您确实想要获取构成已抛出ListBox的对象的ListBoxItem,则可以执行以下操作:

ListBoxItem item = myListBox.ItemContainerGenerator.ContainerFromItem(objectIWantToSelect);
item.IsSelected = true;

You have various options: 您有多种选择:

  • use the SelectedItem or SelectedIndex property of the ListBox control 使用ListBox控件的SelectedItem或SelectedIndex属性
  • if you have the ListBoxItem and not the parent ListBox, use ItemsControl.ItemsControlFromItemContainer(listboxitem) to retrieve the parent ListBox (and use the previous properties) 如果您有ListBoxItem而不是父ListBox,请使用ItemsControl.ItemsControlFromItemContainer(listboxitem)来检索父ListBox(并使用以前的属性)
  • use the ICollectionView interfaces (CollectionViewSource.GetDefaultView) and its methods(MoveCurrentToNext, MoveCurrentToPrevious) 使用ICollectionView接口(CollectionViewSource.GetDefaultView)及其方法(MoveCurrentToNext,MoveCurrentToPrevious)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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