繁体   English   中英

以编程方式更改选定的ListBoxItem

[英]Programmatically change selected ListBoxItem

是否可以从Windows Presentation Foundation中的Code-Behind更改选定的ListBoxItem

实际上,这是一个非常简单的任务,我有一个NextPrevious按钮,它们代表ListBox的下一个和上一个项目。 但是, myListBox.items当然是我存储在ListBox中的对象的对象表示。

因此,如何获取ListBoxItem来设置IsSelected属性?

在您的情况下,可能更容易做,因为您正在执行Previous和Next,只需增加SelectedIndex:

//Increment
if(myListBox.SelectedIndex < myListBox.Items.Count -1)
     myListBox.SelectedIndex++;

//Decrement
if(myListBox.SelectedIndex > 0)
     myListBox.SelectedIndex--;

如果您确实想要获取构成已抛出ListBox的对象的ListBoxItem,则可以执行以下操作:

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

您有多种选择:

  • 使用ListBox控件的SelectedItem或SelectedIndex属性
  • 如果您有ListBoxItem而不是父ListBox,请使用ItemsControl.ItemsControlFromItemContainer(listboxitem)来检索父ListBox(并使用以前的属性)
  • 使用ICollectionView接口(CollectionViewSource.GetDefaultView)及其方法(MoveCurrentToNext,MoveCurrentToPrevious)

暂无
暂无

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

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