簡體   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