![](/img/trans.png)
[英]Changing the SelectedIndex of Multiple Select Listbox to the last selected item
[英]Changing the SelectedIndex in a ListBox programmatically after removing an Item
我想从 ListBox 中删除项目并将所选索引设置为下一个项目。
<ListBox x:Name="lstBox" KeyDown="lstBox_KeyDown">
<ListBoxItem>A</ListBoxItem>
<ListBoxItem>B</ListBoxItem>
<ListBoxItem>C</ListBoxItem>
<ListBoxItem>D</ListBoxItem>
<ListBoxItem>E</ListBoxItem>
</ListBox>
除非我使用箭头键,否则此代码按预期工作。 例如,如果我删除“B”,则下一个选定项目是“C”。 但是,使用 cursor 向下将 select 第一项“A”而不是“D”。
private void lstBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Delete)
{
if (lstBox.SelectedIndex == -1)
return;
int currentIndex = lstBox.SelectedIndex;
int newIndex = lstBox.SelectedIndex;
//in case the last item was deleted
if (newIndex == lstBox.Items.Count - 1)
newIndex--;
lstBox.Items.RemoveAt(currentIndex);
lstBox.SelectedIndex = newIndex;
}
}
设置新索引后,我已经尝试将焦点设置到 ListBox。 但这无济于事。
lstBox.SelectedIndex = newIndex;
lstBox.Focus();
我该如何解决?
此问题是由于当您删除一项时,ListBox 失去焦点。 因此,为了使您的箭头键起作用,您还必须将焦点设置在列表框的选定项上
<ListBox x:Name="lstBox" KeyDown="lstBox_KeyDown" SelectionChanged="LstBox_OnSelectionChanged">
<ListBoxItem>A</ListBoxItem>
<ListBoxItem>B</ListBoxItem>
<ListBoxItem>C</ListBoxItem>
<ListBoxItem>D</ListBoxItem>
<ListBoxItem>E</ListBoxItem>
</ListBox>
private void LstBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
var item = (ListBoxItem)lstBox.ItemContainerGenerator.ContainerFromItem(lstBox.SelectedItem);
if (item != null)
item.Focus();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.