[英]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
. 实际上,这是一个非常简单的任务,我有一个
Next
和Previous
按钮,它们代表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: 您有多种选择:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.