删除项目后以编程方式更改 ListBox 中的 SelectedIndex

Changing the SelectedIndex in a ListBox programmatically after removing an Item

我想从 ListBox 中删除项目并将 selected 索引设置为下一个项目。

<ListBox x:Name="lstBox" KeyDown="lstBox_KeyDown">
            <ListBoxItem>A</ListBoxItem>
            <ListBoxItem>B</ListBoxItem>
            <ListBoxItem>C</ListBoxItem>
            <ListBoxItem>D</ListBoxItem>
            <ListBoxItem>E</ListBoxItem>
</ListBox>

除非我使用箭头键,否则此代码将按预期工作。例如,如果我删除 "B",下一个 selected 项目是 "C"。 但是使用光标向下将 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();
}