简体   繁体   English

删除项目后以编程方式更改列表框中的 SelectedIndex

[英]Changing the SelectedIndex in a ListBox programmatically after removing an Item

I would like to remove items from a ListBox and set the selected index to the next 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>

This code works as intended unless i use the arrow keys.除非我使用箭头键,否则此代码按预期工作。 If i delete "B" for instance the next selected item is "C".例如,如果我删除“B”,则下一个选定项目是“C”。 However using cursor down will select the first item "A" instead of "D".但是,使用 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;
            }
        }

I have already tried to set the focus to the ListBox after setting the new index.设置新索引后,我已经尝试将焦点设置到 ListBox。 But it doesn't help.但这无济于事。

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

How can i fix that?我该如何解决?

This issue is due to the fact that when you are removing one item, ListBox loses the focus.此问题是由于当您删除一项时,ListBox 失去焦点。 So in order to make your arrow keys work, you will also have to set the focus on Selected Item of the 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM