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

问题描述 投票:1回答:1

我想从列表框中删除项目,并将选定的索引设置为下一个项目。

<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”。 但是使用光标向下将选择第一项“ 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;
            }
        }

我已经尝试在设置新索引后将焦点设置到列表框。但这没有帮助。

lstBox.SelectedIndex = newIndex;
lstBox.Focus();

我该如何解决?

c# wpf listbox
1个回答
0
投票

此问题是由于以下事实:当您删除一项时,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();
}
© www.soinside.com 2019 - 2024. All rights reserved.